异步等待数据库花费时间

问题描述 投票:0回答:1

就我而言,我需要在应用程序的开头从数据库中加载一些数据。但是我无法加载数据,因此我测试了我的代码出了什么问题,发现在await database中花费了一些时间,并且代码跳过了此功能并执行其他操作。结果,我在创建UI之后会获取数据,因此无法显示数据。有什么办法解决吗?这是我的代码和结果-

dbhelper.dart

    static Database db_instance;

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

      initDB() async{
        var dbDir = await getDatabasesPath();
        var dbPath = join(dbDir, "test.db");
        ByteData data = await rootBundle.load(join("assets","test.db"));
        List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
        await File(dbPath).writeAsBytes(bytes);

        var db = await openDatabase(dbPath);
        return db;
      }

    getTest() async{
     print("Test1");
     var db_connection = await db;
     print("Test2");
     List<Map> list = await db_connection.rawQuery('SELECT * FROM $TABLE_NAME Where id= 1');
     print("Test3");
     for(int i=0;i<list.length;i++){
       print("Test4");
       id = list[i]['id'];
       name = list[i]['name'];
       phone = list[i]['phone'];
      }
     print("Test5"+name);
   }

main.dart

getContactsFromDB()async{
  var dbHelper = DBHelper();
  dbHelper.getTest();
  print("Test6"+phone);
}

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

结果

I/flutter (13203): Test1
I/flutter (13203): Test6 // skip Test2,3,4,5 and jump to another operation and data not collected
I/flutter (13203): Test2
I/flutter (13203): Test3
I/flutter (13203): Test4
I/flutter (13203): Test5 Zin
asynchronous flutter dart async-await
1个回答
0
投票

只需使用FutureBuilder。像这里的东西:

Widget projectWidget() {
   return FutureBuilder(
     future: getContactsFromDB(),
     builder: (context, snapshot) {
       if (snapshot.connectionState == ConnectionState.done) {
           return Container();
       } else {
           return CircularProgressIndicator();
       }
    }
  ) 
}
© www.soinside.com 2019 - 2024. All rights reserved.