Asynchronous 异步等待数据库需要时间

Asynchronous 异步等待数据库需要时间,asynchronous,flutter,dart,async-await,Asynchronous,Flutter,Dart,Async Await,在我的例子中,我需要在应用程序开始时从数据库加载一些数据。但是我无法加载数据,所以我测试了代码的错误,发现在等待数据库中需要一些时间,代码跳过此函数并执行其他操作。结果,我在创建UI之后获得了数据,因此无法显示数据。有办法解决吗? 这是我的代码和结果- dbhelper.dart static Database db_instance; Future<Database> get db async{ if(db_instance == null)

在我的例子中,我需要在应用程序开始时从数据库加载一些数据。但是我无法加载数据,所以我测试了代码的错误,发现在
等待数据库中需要一些时间,代码跳过此函数并执行其他操作。结果,我在创建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);
   }
结果

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

只需使用FutureBuilder。比如这里:

Widget projectWidget() {
   return FutureBuilder(
     future: getContactsFromDB(),
     builder: (context, snapshot) {
       if (snapshot.connectionState == ConnectionState.done) {
           return Container();
       } else {
           return CircularProgressIndicator();
       }
    }
  ) 
}

尝试使用future builder,以便在future builder功能完成后呈现UI future builder为我工作感谢您的帮助。
Widget projectWidget() {
   return FutureBuilder(
     future: getContactsFromDB(),
     builder: (context, snapshot) {
       if (snapshot.connectionState == ConnectionState.done) {
           return Container();
       } else {
           return CircularProgressIndicator();
       }
    }
  ) 
}