11

因为 initState 方法在这里不可覆盖,所以在 consumerWidget 中初始化事物的解决方案是什么?

4

3 回答 3

21

更新

Riverpod v1.0.0

您可以使用ConsumerStatefulWidgetConsumerState

final helloWorldProvider = Provider((_) => 'Hello world');

class RiverpodExample extends ConsumerStatefulWidget {
  @override
 _RiverpodExampleState createState() => _RiverpodExampleState();
}

class _RiverpodExampleState extends ConsumerState<Example> {

  @override
  void initState() {
    super.initState();

    final value = ref.read(helloWorldProvider);

  }

  @override
  Widget build(BuildContext context) {
    final value = ref.watch(helloWorldProvider);

    return Text(value); // Hello world
  }
}

高达 Riverpod v0.14.0+3

您必须使用StatefulWidget并返回Consumer作为该build方法的根小部件。

消费者

Consumer 可用于监听 StatefulWidget 内的提供者,或在提供者更新时重建尽可能少的小部件。

final helloWorldProvider = Provider((_) => 'Hello world');

class RiverpodExample extends StatefulWidget {
  @override
  _RiverpodExampleState createState() => _RiverpodExampleState();
}

class _RiverpodExampleState extends State<Example> {

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, watch, child) {
        final value = watch(helloWorldProvider);
        return Text(value); // Hello world
      },
    );
  }
}
于 2020-10-06T01:10:29.673 回答
3

我不完全确定如何回答您的问题,因为我没有与 ConsumerWidget 合作过。我认为这个想法是将您的大部分状态保留在提供者中。

但是,我想建议将hooks_riverpodflutter_hooks一起使用(同一个开发人员)。

这使得保持小部件本地状态变得简单,并且还提供了对提供程序的轻松访问。

例如:

class Example extends HookWidget {
  const Example({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final test = useProvider(Test.provider());

    final controller = useTextEditingController();
    final loading = useState(false);
    final buttonText = useState('Change me!');

    return Column(
      children: [
        TextField(controller: controller),
        if (!loading) RaisedButton(
          onPressed: () async {
            loading.value = true;
            await Future.delayed(const Duration(seconds: 1));
            buttonText.value = controller.text;
            loading.value = false;
          }
          child: Text(buttonText.value),
        ),
        if (loading) const CircularProgressIndicator(),
        // Do something with providers, etc.
      ],
    ),
  );
}

只是一个简单的例子,但是有很多资源(flutter_hookshooks_riverpod)可以帮助你。此外,请查看开发人员提供的有关 Riverpod 钩子使用的示例。

于 2020-10-05T15:15:39.267 回答
0

我可能迟到了,但是随着即将推出的 Riverpod 1.0.0,您将能够使用https://pub.dev/documentation/flutter_riverpod/1.0.0-dev.2/flutter_riverpod/ConsumerStatefulWidget-class.htmlhttps:// /pub.dev/documentation/flutter_riverpod/1.0.0-dev.2/flutter_riverpod/ConsumerState-class.html,这正是你想要的。

于 2021-07-02T13:32:18.187 回答