简体   繁体   English

在 flutter 中使用 Snack Bar 和 Navigator 时,如何修复“不要使用 BuildContexts accros async gaps”

[英]How do I fix "Do not use BuildContexts accros async gaps" when using Snack Bar and Navigator in flutter

This is my code这是我的代码


  _signinRouter(
    userId,
    BuildContext context, {
    phone = false,
    email = false,
    googleSignUp = false,
    userData,
  }) async {
    NetworkController network = NetworkController();

    setState(() {
      _isLoading = true;
    });

    CallResponse response = await network.fetchUserData(
      userId,
      phone: phone,
      email: email,
    );

    setState(() {
      _isLoading = false;
    });
    if (response.status == 1) {
      debugPrint(response.msg.toString());
      //IF USER DATA IS FOUND

      showSnackBar('User account exists', context);
    } else {
      //Since network returns one or zero, 1 for the success of request and 0 for both server error and failure of request
      //Response msg will return null if user was not found and it will return an actual server failure msg if it was a server error
      if (response.msg == 'null') {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => (googleSignUp)
                ? GooglePostSignUp(userData: userData)
                : ServerSignUp(phoneNumber: userId, userData: userData),
          ),
        );
      } else {
        showSnackBar(response.msg, context);
      }
    }
  }
}

I am calling the function within a stateful widget and I defined a function to help in calling the snack bar, my app relies heavily on snack bars and I have this same error all across my files.我在一个有状态的小部件中调用 function,我定义了一个 function 来帮助调用小吃店,我的应用程序严重依赖小吃店,我的所有文件都有同样的错误。 This is the snack bar function这是小吃店 function

void showSnackBar(String? value, BuildContext context) {
  ScaffoldMessenger.of(context).hideCurrentSnackBar();
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text(
        value!,
        style: p2(
          false,
        ),
      ),
      duration: const Duration(seconds: 2),
      action: SnackBarAction(
        label: 'Close',
        textColor: themeColor,
        onPressed: () {
          ScaffoldMessenger.of(context).hideCurrentSnackBar();
        },
      ),
    ),
  );
}

I can call the my custom snack bar from anywhere with in my project easily.我可以在我的项目中轻松地从任何地方调用我的自定义小吃店。

I can trick the IDE and lint by removing the Buildcontext type in the function but it not practical, i can check if the widget is mounted before calling the snackbar but i dont think it is very practical???我可以通过删除 function 中的 Buildcontext 类型来欺骗 IDE 和 lint,但它不实用,我可以在调用 snackbar 之前检查小部件是否已安装,但我认为它不太实用???

the simplest way is just put最简单的方法就是放

if (!mounted) return;

for void functions before you call snackbar or anything that requires context.在您调用 snackbar 或任何需要上下文的内容之前获取 void 函数。

I know you are thinking of app performance in mind, Oh: wait.我知道您在考虑应用程序性能,哦:等等。 flutter already did that for you.), You don't need to work around it except if you have time and energy. flutter 已经为您完成了。),除非您有时间和精力,否则您无需解决它。 Note that, the context has to be passed every time and so checking the context mount every time is not "i don't think it is very practical" situation请注意,每次都必须传递上下文,因此每次都检查上下文挂载并不是“我认为这不太实用”的情况

Things like this I call (The warning error) .像这样的事情我称之为(The warning error) When working with async functions within a context that is likely to be lost due to nesting.在可能因嵌套而丢失的上下文中使用async函数时。 You need to handle it with care.你需要小心处理它。

One way to do that is by checking for the widget-mounted state. basically, Don't use context after async if you're not sure your widget is mounted.一种方法是检查挂载的小部件 state。基本上,如果不确定小部件是否已挂载,请不要在异步后使用context

To be sure use the following:为确保使用以下内容:

if (!mounted) return; // check before calling `Navigator`
Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => (googleSignUp)
                ? GooglePostSignUp(userData: userData)
                : ServerSignUp(phoneNumber: userId, userData: userData),
          ),
        );

To make the code short-hand just do the normals:!!要使代码简写,只需执行法线即可:!! :) break the code down in the same file!! :) 在同一个文件中分解代码!!

Bye.再见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在颤振中使用 tflite 处理自定义模型时,应用程序崩溃。 我如何解决它? - Application is crashing when working with custom model using tflite in flutter. How do i fix it? 单击底部导航时无法导航 Flutter - Cant Do Navigator when clicking bottomNav Flutter 如何修复 Flutter for Android 问题? - How do I fix a Flutter for Android issue? 仅在Android Gmail中的电子邮件中出现差距。我该如何解决这个问题? - Gaps appearing in an email in only Android Gmail. How do I fix this issue? 我什么时候在 Flutter 中使用 setState? - When do I use setState in Flutter? 如何使用画家在 Flutter 中编写自定义底部导航栏 - How can I code Custom Bottom Navigator Bar in Flutter with painter 使用 Glide 时如何修复崩溃的应用程序 - How do I fix crashing Application when using Glide 使用jetpack compose时在android测试中测试小吃吧 - Testing snack bar in android testing when using jetpack compose 如何修复“错误:Flutter 目录不是 GitHub 项目的克隆。” 尝试安装 flutter 时出错? - How do I fix the "Error: The Flutter directory is not a clone of the GitHub project." error when I'm trying to install flutter? 如何将ViewPager与AHBottomNavigation栏一起使用? - How do I use a ViewPager with the AHBottomNavigation bar?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM