You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中ChangeNotifierProvider未监听更新导致FutureProvider路径无法修改

问题原因
  • MyApp中获取Location实例时设置了listen: false,导致Location状态更新发送notifyListeners()时,不会触发MyApp的build方法重新执行,FutureProvider的初始化逻辑永远只会取第一次的默认值none。
  • 普通FutureProvider的create方法只会在Provider被创建时执行一次,就算后续MyApp重绘,默认也不会重新执行create方法拉取新路径对应的数据。
修复方案

推荐使用官方提供的ProxyProvider实现Provider之间的依赖绑定,ProxyProvider会自动监听依赖的Location状态变化,每次状态更新都会重新执行数据拉取逻辑,替换main.dart中MultiProvider的配置即可:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        // 替换原有FutureProvider为ProxyProvider,绑定对Location的依赖
        ProxyProvider<Location, Future<List<Report>>>(
          // 每次Location变化都会自动触发update方法,生成新的请求Future
          update: (context, location, previous) =>
              Collection<Report>(path: '${location.getLocation}/data/reports')
                  .getUsers(),
        ),
      ],
      child: MaterialApp(
        routes: {
          '/': (context) => LocationLogin(),
          '/login': (context) => LoginScreen(),
          '/home': (context) => HomeScreen(),
        },
        // 原有主题配置保持不变
        theme: ThemeData(
          fontFamily: 'Nunito',
          bottomAppBarTheme: BottomAppBarTheme(
            color: Colors.black87,
          ),
          brightness: Brightness.dark,
          buttonTheme: ButtonThemeData(),
        ),
      ),
    );
  }
}

调整后在使用List<Report>的页面,注意新增加载状态的判断,适配每次位置切换时的请求等待过程即可。

内容的提问来源于stack exchange,提问作者taco-tuesday

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:24:00