gpt4 book ai didi

asynchronous - Flutter 提取异步到分隔符类和方法

转载 作者:IT王子 更新时间:2023-10-29 07:03:03 25 4
gpt4 key购买 nike

My implementation repository

main 方法中,我有这行代码可以连接到数据库并正常工作

Future<void> main() async {
final database = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();

final userDao = database.userDao;

runApp(MaterialApp(...);
}

现在我正在尝试使用这些代码

  final database = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
final userDao = database.userDao;

来自类,例如:

Future<void> main() async {
MyDatabase myDatabase = MyDatabase();
final userDao = myDatabase.userDao;

runApp(MaterialApp(...);
}

不幸的是,我在这个实现中为 userDao 得到了 null,我认为在那个女巫中我使用 async 我应该改变它并使用 然后()

class MyDatabase {
UserDao userDao;

Future<UserDao> initialDatabase() async {
final database = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
return database.userDao;
}
}

@dao
abstract class UserDao{
@Query('SELECT * FROM User LIMIT 1')
Stream<User> getUserInfo();

@insert
Future<void> insertUserInformation(User user);
}

更新:范围模型的实现解决方案

class MydbModel extends Model {
MyDatabase myDatabase = MyDatabase();
Future _doneFuture;

MydbModel() {
_doneFuture= myDatabase.initialDatabase();
}

Future get initializationDone => _doneFuture;
}

class MyDatabase {
AppDatabase db;
UserDao userDao;

Future<void> initialDatabase() async {
db = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
}

UserDao getUserDao() {
return db.userDao;
}
}

main() {
runApp(MaterialApp(
title: 'floor sample',
home: App(),
));
}

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

@override
State<App> createState() => _AppState();
}

class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: ScopedModel(
model: MydbModel(),
child: ScopedModelDescendant<MydbModel>(
builder: (context, _, model) => StreamBuilder<User>(
stream: model.myDatabase.userDao.getUserInfo(),
builder: (_, snapshot) {
if (!snapshot.hasData) {
return Text('user not found');
} else {
return Text('user found');
}
},
),
),
),
);
}
}

最佳答案

对于给定的类实现,您应该调用该函数并等待它完成:

MyDatabase myDatabase = MyDatabase();
final userDao = await myDatabase.initialDatabase();

或者,如果您不想每次都重新创建数据库实例,请考虑将其分配给类成员

class MyDatabase {
AppDatabase db;

Future<void> initDb() async {
db = await $FloorAppDatabase.databaseBuilder('flutter_database.db').build();
}

UserDao getUserDao() {
return db.userDao;
}

// here may be other functions that use db
}

然后像这样使用它

MyDatabase myDatabase = MyDatabase();
await myDatabase.initDb();
final userDao = myDatabase.getUserDao();
// here you can call other functions from class

关于asynchronous - Flutter 提取异步到分隔符类和方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56507560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com