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

时间:2019-06-08 15:08:32

标签: asynchronous flutter dart

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(...);
}

不幸的是,在此实现中,我为null获得了userDao,我认为我使用async的女巫应该对此进行更改并使用then()

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');
              }
            },
          ),
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

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

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