【问题标题】:Flutter: async await颤振:异步等待
【发布时间】: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


    【解决方案1】:

    在这种情况下,您可以使用FutureBuilder,使用这个您将有不同的状态,就像StreamBuilder,您可以根据状态显示不同的小部件,直到解决未来并且您拥有数据。

    我已经对您的代码进行了一些重构,以使其与 FutureBuilder 一起工作,我也将其更改为无状态,在这种情况下,它将显示 CircularProgressIndicator,直到解决未来,它会还可以处理错误和缺少数据。

    class Profile extends StatelessWidget {
      const Profile({Key key}) : super(key: key);
    
      Future<List<Recipe>> getUserRecipes(UserData userData) async {
        return await DatabaseService().findUserRecipes(userData.uid);
      }
    
      Widget ifHasRecipes(List<Recipe> myRecipes) {
        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) {
              return Scaffold(
                body: SafeArea(
                  child: FutureBuilder(
                    future: getUserRecipes(snapshot.data),
                    builder: (context, futureSnapshot) {
                      if (futureSnapshot.hasError)
                        return Text('Error: ${futureSnapshot.error}');
                      switch (futureSnapshot.connectionState) {
                        case ConnectionState.none:
                          return Center(child: CircularProgressIndicator());
                        case ConnectionState.waiting:
                          return Center(child: CircularProgressIndicator());
                        case ConnectionState.active:
                          return Center(child: CircularProgressIndicator());
                        case ConnectionState.done:{
                          if (futureSnapshot.hasData) {
                            List<Recipe> myRecipes = futureSnapshot.data;
                            return Column(
                              children: <Widget>[
                                //widgets using userData
                                ifHasRecipes(myRecipes),
                              ],
                            );
                          }
                          return Text('There\'s no available data.');
                        }
                      }
                      return null;
                    },
                  ),
                ),
              );
            } else {
              return Scaffold(
                body: Center(
                  child: SpinKitRipple(),
                ),
              );
            }
          },
        );
      }
    }
    

    【讨论】:

    • 非常感谢,这完美!从未听说过 FutureBuilder。
    【解决方案2】:

    如果我正确理解代码,解决方案是通过在getUserRecipes() 方法中添加setState((){}); 来解决未来问题时重建小部件:

    Future<void> getUserRecipes(UserData userData) async {
      myRecipes = await DatabaseService().findUserRecipes(userData.uid);
      setState((){});
    }
    

    (如果您将值分配给状态,则不必返回该值,而是直接访问它。)

    顺便说一句,您可以使用三元运算符(或只是常规条件)来做条件 UI。用这个代替ifHasRecipes(),

    (myRecipes != null && myRecipes != []) ?
      FavoritesHomePage(
              recipes: myRecipes, scrollDirection: Axis.vertical, title: 'Your recipes',)
      : Text('You have no favorites yet')
    

    如果您遇到此错误,请在 pubspec.yaml 中将您的最低 SDK 版本增加到 2.6.0

    【讨论】:

    • 非常感谢,这行得通!但是,在使用浏览量小部件和您的解决方案时,也必须修复此错误:E/flutter (12544): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose( ): _HomePageState#2b9b0(生命周期状态:已失效,未挂载)
    • E/flutter (12544):如果您在状态对象上为不再出现在窗口小部件树中的窗口小部件调用 setState()(例如,其父窗口小部件不再包含该窗口小部件),则会发生此错误在其构建中)。当代码从计时器或动画回调中调用 setState() 时,可能会发生此错误。 E/flutter (12544):首选解决方案是取消计时器或停止在 dispose() 回调中收听动画。另一种解决方案是在调用 setState() 之前检查该对象的“已安装”属性,以确保该对象仍在树中。
    • E/flutter (12544):如果调用 setState(),则此错误可能表示内存泄漏,因为另一个对象在从树中删除此 State 对象后仍保留对该对象的引用。为避免内存泄漏,请考虑在 dispose() 期间中断对此对象的引用。
    猜你喜欢
    • 2020-02-16
    • 2021-03-28
    • 2019-05-07
    • 2022-01-22
    • 2022-06-19
    • 2020-10-25
    • 2019-08-31
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多