【问题标题】:How do I get data from an sqflite table and display it as a % inside text widget如何从 sqflite 表中获取数据并将其显示为文本小部件内的 %
【发布时间】:2020-02-05 01:45:14
【问题描述】:

import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseHelper {

  static final _databaseName = "MyDatabase.db";
  static final _databaseVersion = 1;

  static final table = 'my_table';

  static final columnId = '_id';
  static final columnName = 'name';
  static final columnAge = 'age';

  // make this a singleton class
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // only have a single app-wide reference to the database
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion,
        onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnName TEXT NOT NULL,
            $columnAge INTEGER NOT NULL
          )
          ''');
  }

  // Helper methods

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await instance.database;
    return await db.insert(table, row);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<double> queryRowCount() async {
    Database db = await instance.database;
    List<Map<String, dynamic>> x = await db.rawQuery('SELECT COUNT(*) FROM $table');
    int rowCount = Sqflite.firstIntValue(x);
    return rowCount.toDouble();
  }

  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(Map<String, dynamic> row) async {
    Database db = await instance.database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
  }

  Future<List<Map<String, dynamic>>> queryOmnivore() async {
    Database db = await instance.database;
    return await db.query(table, where: '$columnName = ?', whereArgs: ['omnivore']);
  }

  Future<List<Map<String, dynamic>>> queryPescatarian() async {
    Database db = await instance.database;
    return await db.query(table, where: '$columnName = ?', whereArgs: ['pescatarian']);
  }

  Future<List<Map<String, dynamic>>> queryVegetarian() async {
    Database db = await instance.database;
    return await db.query(table, where: '$columnName = ?', whereArgs: ['vegetarian']);
  }

  Future<int> queryVegetarianCount() async {
    var vegList = await queryVegetarian();
    int count = vegList.length;
    return count;
  }

  Future<double> queryOmnivoreCount() async {
    var omniList = await queryOmnivore();
    int omniCount = omniList.length;
    return omniCount.toDouble();
  }

  Future<double> calcOmnivorePercentage() async {
    var x = await queryOmnivoreCount();
    var y = await queryRowCount();
    double omniPercentage = (x / y) * 100;
    return omniPercentage;
  }
}

大家好!

我希望有人可以帮助我吗?!

我试图弄清楚如何从我创建的 sqflite 表中取出数据,执行计算,将其表示为其他值的百分比,并将其显示在应用程序的文本小部件中。

我实际上已经设法使用以下代码在控制台中打印结果:

void omnivorePercentageQ() async {
    final omni = await dbHelper.calcOmnivorePercentage();
    print('omnivore percentage: ${omni.toStringAsFixed(1)}');
  } 

但我不知道如何让它显示在应用程序本身的文本小部件中。

任何想法将不胜感激!

谢谢,

杰森

【问题讨论】:

    标签: flutter sqflite


    【解决方案1】:

    您离答案不远了,并且已经掌握了所需计算的值。如我所见,您不需要将任何参数传递给函数,因此我建议使用 futurebuilder:

    return FutureBuilder(
        future: dbHelper.calcOmnivorePercentage(),
        builder: (context, AsyncSnapshot<double> snapshot) {
          if (snapshot.hasData) {
            return Center( child: Text('${snapshot.data.toStringAsFixed(1)}'),);
          }else
          return Center(
            child: CupertinoActivityIndicator(),
          );
        });
    

    Future Builder 类https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html 用于管理依赖于期货的小部件,因为您的计算和数据库查询是异步的,您可以检查其状态(如在 snapshot.hasData 中的小部件内部)。该条件检查未来是否已经完成,否则显示一个指标。希望对你有帮助

    【讨论】:

    • 您好!非常感谢你帮助我!效果很好!在过去的 48 小时里,我真的花了很多时间试图弄明白,非常感谢你!
    • 没问题,很高兴为您提供帮助,因为我一直处于与您相同的位置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多