实时计算记录和 return 总记录数,然后将其显示为小部件中的文本

Count records and return total records number in real time then display it as text in a widget

我正在尝试获取名为 'persons' 的 sqlite 数据库 table 的记录总数。获得记录总数后,我想在 Text() 小部件内的 Container 小部件中显示此数字。我尝试了不同的方法来完成这项工作,但我使用的任何方法都不起作用。

下面是db_helper.dart文件。需要 return 记录总数的函数被定义为 countPeople.

import 'dart:async';
import 'dart:io' as io;
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

/// models

import 'package:path/path.dart';

class DBHelper {
  static Database db_instance;

  Future<Database> get db async {
    if (db_instance == null) {
      db_instance = await initDB();
    }
    return db_instance;
  }

  initDB() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'development.db');
    var db = await openDatabase(path, version: 1, onCreate: onCreateFunc);
    return db;
  }

  void onCreateFunc(Database db, int version) async {
    // create table
    await db.execute('''CREATE TABLE persons(
      id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, nickname TEXT, country_id INTEGER, role TEXT, created DATETIME, updated DATETIME
    );''');
  }

  /**
   * crud functions
   */

  void countPeople() async {
    var db_connection = await db;
    final count = Sqflite.firstIntValue(
        await db_connection.rawQuery('SELECT COUNT(*) FROM persons'));
    // assert(count == 2);
    print('people count: $count');
  }
  Future<List<Person>> getAllPersons() async {
    final db_connection = await db;
    var response = await db_connection
        .rawQuery("SELECT * FROM persons ORDER BY created DESC");
    // print(response);
    List<Person> list = response.map((c) => Person.fromJson(c)).toList();
    return list;
  }

  // add new person
  void addNewPerson(Person person) async {
    var db_connection = await db;
    String query = """
        INSERT INTO persons(name,nickname,role,created,updated) VALUES('${person.name}','${person.nickname}', '${person.role}','${person.created}', '${person.updated}')
        """;
    await db_connection.transaction((transaction) async {
      // print(query);
      return await transaction.rawInsert(query);
    });
  }

下面是people_count.dart文件。这是我希望在 Text() 小部件中显示总记录数的地方。

import 'package:flutter/material.dart';
import 'package:com.example.simple_app/utils/db_helper.dart';
import 'package:com.example.simple_app/models/person.dart';
import 'package:com.example.simple_app/pages/main_user_registration/create_account.dart';

class MainUserRegistration extends StatefulWidget {
  MainUserRegistration({Key key}) : super(key: key);

  @override
  _MainUserRegistrationState createState() => _MainUserRegistrationState();
}

var dbHelper = DBHelper();

class _MainUserRegistrationState extends State<MainUserRegistration> {
  var result = dbHelper.countPeople();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text('Loans'),
      ),
      body: new Container(
        child: Row(
          children: <Widget>[
            Text('all persons: ${dbHelper.countPeople()}'), // the total number of records should appear here
          ],
        ),
      ),
    );
  }
}

您可能应该尝试使用 setState() 来更改 initState 上的异步数据,这是 people_count.dart 的样子:

import 'package:flutter/material.dart';
import 'package:com.example.simple_app/utils/db_helper.dart';
import 'package:com.example.simple_app/models/person.dart';
import 'package:com.example.simple_app/pages/main_user_registration/create_account.dart';

class MainUserRegistration extends StatefulWidget {
  MainUserRegistration({Key key}) : super(key: key);

  @override
  _MainUserRegistrationState createState() => _MainUserRegistrationState();
}

var dbHelper = DBHelper();

class _MainUserRegistrationState extends State<MainUserRegistration> {
  int number = -1;

  void countPeople() async {
    int count = await dbHelper.countPeople();
    setState(() => number = count);

  @override
  void initState() {
    super.initState();
    countPeople();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text('Money Lender'),
      ),
      body: new Container(
        child: Row(
          children: <Widget>[
            Text('all persons: ${number}'), // the total number of records should appear here
          ],
        ),
      ),
    );
  }
}

db_helper.dart中的人数统计函数应该return人数:

Future<int>countPeople() async {
    var db_connection = await db;
    final count = Sqflite.firstIntValue(
        await db_connection.rawQuery('SELECT COUNT(*) FROM persons'));
    // assert(count == 2);
    print('people count: $count');
    return count;
  }