Riverpod组合Provider时DropdownButton值无法更新的问题求助
你的问题核心在于没有正确更新cityProvider的状态——只是修改了局部变量city,这不会触发Riverpod的状态监听机制,所以UI和关联的weatherProvider都不会同步更新。
关键修改点
在DropdownButton的onChanged回调里,不能直接给局部变量city赋值,而是要通过StateProvider的notifier来更新状态:
onChanged: (value) { if (value != null) { ref.read(cityProvider.notifier).state = value; } },
修改后的完整代码
final cityProvider = StateProvider<String>((ref) => 'Country one'); final weatherProvider = StateProvider((ref) { final city = ref.watch(cityProvider); return city == 'Country one' ? '25' : city == 'Country two' ? '30' : '50'; }); class ExampleSeven extends StatelessWidget { const ExampleSeven({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Combining Providers with Firebase'), ), body: Center( child: ElevatedButton( onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const SecondScreen(), )); }, child: const Text('Go to next Page')), ), ); } } class SecondScreen extends ConsumerWidget { const SecondScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { String city = ref.watch(cityProvider); final weather = ref.watch(weatherProvider); return Scaffold( appBar: AppBar( title: const Text('Combining Providers Second Screen'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ DropdownButton( value: city, items: const [ DropdownMenuItem( value: 'Country one', child: Text('Country one'), ), DropdownMenuItem( value: 'Country two', child: Text('Country two'), ), DropdownMenuItem( value: 'Country three', child: Text('Country three'), ), ], onChanged: (value) { if (value != null) { ref.read(cityProvider.notifier).state = value; } }, ), Text( weather, style: const TextStyle(fontSize: 40), ), ], ), )); } }
额外说明
- 不需要改成
ConsumerStatefulWidget,ConsumerWidget完全可以处理这种场景。 - 也不需要用
listen,watch已经能正确监听cityProvider的状态变化并重建UI。 - 给
build方法的第二个参数加上WidgetRef类型标注,避免隐式类型带来的潜在问题。
内容的提问来源于stack exchange,提问作者Muhammad Tawil
相关产品推荐
相关产品推荐

