例如,我制作了一个简单的单例类以用于颤动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;
}
答案 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: ..,
);
},
);
我使用了FutureBuilder
到await
的{{1}},并在加载未来时创建了Future
。