“ Future <Stream>”不是“ Stream”类型的子类型

时间:2019-06-09 17:06:57

标签: flutter dart

例如,我制作了一个简单的单例类以用于颤动StreamBuilder小部件,

StreamBuilder<User>(
  stream: MydbModel.create().then((dao) => dao.getUserStream()) as Stream<User>,
  builder: (_, snapshot) {
    ...
  },
)

MydbModel.create().then((dao) => dao.getUserStream())

返回Future<Stream<User>>,我的演员表仅包含Stream<User>无效。

错误:

> type 'Future<Stream<User>>' is not a subtype of type 'Stream<User>' in type cast

我该如何解决这个问题?

我完成的课程:

class MydbModel{
  UserDao _userDao;

  MydbModel._(this._userDao);
  static Future<MydbModel> create() async => MydbModel._(await initialDatabase());

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

  Stream<User> getUserStream(){
    return userDao.getUserInfo();
  }

  UserDao get userDao=>_userDao;
}

1 个答案:

答案 0 :(得分:1)

您需要先等待Future

FutureBuilder(
  future: MydbModel.create(),
  builder: (BuildContext context, AsyncSnapshot<MydbModel> snapshot) {
    if (!snapshot.hasData) return Container();
    return StreamBuilder(
      stream: snapshot.data.getUserStream(),
      builder: ..,
    );
  },
);

我使用了FutureBuilderawait的{​​{1}},并在加载未来时创建了Future