【问题标题】:Problem with BuildContexts across sync gaps跨异步间隙的 BuildContexts 问题
【发布时间】:2022-12-31 02:14:35
【问题描述】:

我正在尝试通过学习 Angela Yu 课程来学习 Flutter,这似乎有点过时了,我正面临这个问题:“不要在异步间隙中使用 BuildContexts”,在以下代码中;

void getLocationData() async {
    Location location = Location();

    await location.getCurrentLocation();

    NetworkHelper networkHelper = NetworkHelper(
        'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');

    var weatherData = await networkHelper.getData();

    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return LocationScreen(locationWeather: weatherData);
    }));
  }

我试图在网上查看解决方案,但似乎找不到我的查询的答案。任何反馈将不胜感激。

附言我尝试使用:

if (mounted) {
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return LocationScreen(locationWeather: weatherData);
      }));
    }

但它似乎也不起作用。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以尝试使用 WidgetsBinding.instance.addPostFrameCallback 方法来安排在构建完成后进行导航:

    void getLocationData() async {
        Location location = Location();
    
        await location.getCurrentLocation();
    
        NetworkHelper networkHelper = NetworkHelper(
            'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');
    
        var weatherData = await networkHelper.getData();
    
        // Schedule the navigation to occur after the build is complete
        WidgetsBinding.instance.addPostFrameCallback((_) {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return LocationScreen(locationWeather: weatherData);
          }));
        });
      }
    

    或者您可以尝试在 await networkHelper.getData() 块内移动 Navigator.push 调用,如下所示:

    void getLocationData() async {
        Location location = Location();
    
        await location.getCurrentLocation();
    
        NetworkHelper networkHelper = NetworkHelper(
            'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');
    
        var weatherData = await networkHelper.getData();
    
        // Navigate to the LocationScreen after the async call is complete
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          return LocationScreen(locationWeather: weatherData);
        }));
      }
    

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2023-01-15
      • 2023-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2011-04-12
      相关资源
      最近更新 更多