【发布时间】:2019-10-15 09:10:38
【问题描述】:
就我而言,我需要在应用程序开始时从数据库中加载一些数据。但是我无法加载数据,所以我测试了我的代码有什么问题,发现在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
【问题讨论】:
-
尝试使用future builder,所以future builder功能完成后会渲染UI
-
Future Builder 为我工作,感谢您帮助我。
标签: asynchronous flutter dart async-await