flutter 合并提供商Riverpod

3phpmpom  于 2023-01-31  发布在  Flutter
关注(0)|答案(1)|浏览(153)

我试图学习Riverpod,我用下面的例子来合并两个提供者,但dropDownButton的值永远不会改变,并保持为第一个dropDownItem的第一个值,我改变了ConsumerWidget到ConsumerStatefulWidget也没有改变,如果有任何帮助,请.

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, 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) {
                  city = value;
                },
              ),
              Text(
                weather,
                style: const TextStyle(fontSize: 40),
              ),
            ],
          ),
        ));
  }
}

我可能需要改变第一类或需要使用听而不是读?

zengzsys

zengzsys1#

未正确更新提供程序的值。请将onChanged方法更改为

onChanged: (value) {
  ref.read(cityProvider.notifier).state = value!;
},

相关问题