【发布时间】:2020-09-01 11:45:29
【问题描述】:
在我的应用程序的个人资料页面中,我想使用 async/await 函数将未来的对象列表从 firebase 集合保存到变量 (myRecipes)。根据结果列表,我想显示不同的小部件(使用 ifHasRecipes()) - 如果列表结果为 null 或为空,我想显示一个文本小部件,否则我想使用列表视图生成器(FavoritesHomePage 类)。
class Profile extends StatefulWidget {
final FirebaseAuth _auth = FirebaseAuth.instance;
@override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
List<Recipe> myRecipes;
Future<List<Recipe>> getUserRecipes(UserData userData) async {
return myRecipes = await DatabaseService().findUserRecipes(userData.uid);
}
Widget ifHasRecipes() {
if (myRecipes != null && myRecipes != []) {
return FavoritesHomePage(
recipes: myRecipes, scrollDirection: Axis.vertical, title: 'Your recipes',);
} else {
return Text('You have no favorites yet');
}
}
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return StreamBuilder<UserData>(
stream: DatabaseService(uid: user.uid).userData,
builder: (context, snapshot) {
if (snapshot.hasData) {
UserData userData = snapshot.data;
getUserRecipes(userData);
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
//widgets using userData
ifHasRecipes(),
],
),
),
);
} else {
return Scaffold(
body: Center(
child: SpinKitRipple(),),
);
}
});
}
}
如何使这段代码同步?我想运行 getUserRecipes() 并在完成后根据结果返回不同的小部件。
如果我进行热重载,代码会按我的意愿“工作”,但有时当我通过浏览量小部件导航到此个人资料页面时,返回变量 myRecipes 的 async/await 函数在ifHasRecipes() 已构建,然后 myRecipes 为 null(即使它不应该是)...希望这不会太令人困惑,抱歉。
【问题讨论】:
标签: flutter