FutureBuilder 在尝试从 sqflite 加载数据时卡在加载中

FutureBuilder stuck at loading while trying to load data from sqflite

我正在使用 sqflite 存储一些数据。并使用 FutureBuilder 来显示从数据库中获取的数据。但是 FutureBuilder 无法 return 数据,总是卡在加载屏幕上。这是我的数据库代码:

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

class HistoryDatabase {
  HistoryDatabase._init();
  static final HistoryDatabase instance = HistoryDatabase._init();
  static Database? _database;

  Future<Database?> get database async {
    if (_database != null) {
      return _database;
    } else {
      _database = await getDatabase();  //loads database
      return _database;
    }
  }

  void deleteHistory() async {  //deletes data
    final db = await instance.database;
    db?.delete('history');
  }

  Future<List<Map<String, dynamic>>> getHistory() async {  //gets database data
    final db = await instance.database;

    print(db?.query('history'));

    return db?.query('history') as List<Map<String, dynamic>>;
  }

  addHistory(String resultExpr, String result) async {  //adds entry
    final db = await instance.database;
    db?.execute(
      'INSERT INTO history (resultExpr, result) VALUES (?, ?)',
      [resultExpr, result],
    );
  }

  Future<Database> getDatabase() async {  //database loader method
    return openDatabase(
      join(await getDatabasesPath(), 'calculator.db'),
      onCreate: (db, version) {
        return db.execute(
          'CREATE TABLE history(id INTEGER PRIMARY KEY AUTOINCREMENT, resultExpr TEXT NOT NULL, result TEXT NOT NULL)',
        );
      },
      version: 1,
    );
  }
}

这是我的 FutureBuilder 小部件:

class _BottomSheetState extends ConsumerState<BottomSheet> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Map<String, dynamic>>>(
        future: HistoryDatabase.instance.getHistory(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final history = snapshot.data as List<Map<String, dynamic>>;
            return ListView.builder(
              itemCount: history.length,
              itemBuilder: (context, index) {
                final historyIndex = history[index];
                return ListTile(
                  title: Text(historyIndex['resultExpr'].toString()),
                );
              },
            );
          } else {
            return const Center(
                child: CircularProgressIndicator(  //the futurebuilder always shows this widget
              color: Colors.black,
            ));
          }
        });
  }
}

我的编辑器中没有显示任何错误或警告。此外,我确信数据库初始化没有错误,因为我的插入方法运行良好。我在这里犯了什么错误?

你不是在这里等待未来。 在getHistory().

的return语句中添加await
Future<List<Map<String, dynamic>>> getHistory() async {
    final db = await instance.database; 
    //add await
    return await db?.query('history') as List<Map<String, dynamic>>;
}