Riverpod:在ConsumerWidget内部重写initState的替代方法

问题描述

由于initState方法在这里不可覆盖,因此在ConsumerWidget内部初始化事物的解决方案是什么?

解决方法

由于我尚未使用ConsumerWidget,因此我不确定如何回答您的问题。我想这个想法是将您的大部分状态保留在提供程序中。

但是,我建议与hooks_riverpod(相同的flutter_hooks)一起使用developer

这使在小部件的本地状态保持简单,也使提供者易于访问。

例如:

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)可以帮助您。另外,请查看examples from the developer关于Riverpod钩子用法。

,

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

消费者

消费者可以用来监听StatefulWidget或 在提供程序更新时重建尽可能少的小部件。

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

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

class _RiverpodExampleState extends State<Example> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context,watch,child) {
        final value = watch(helloWorldProvider);
        return Text(value); // Hello world
      },);
  }
}
,

我可能会迟到,但随着即将发布的 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,这正是您想要的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...