我有一个按钮,使用一个计数器Provider 与Riverpod,我想添加一个本地状态isLoading到按钮.

虽然我可以在build方法中完成这一切,但我想知道是否有一种方法可以将状态提升到实例级,以便Btn类中的其他方法也可以访问此状态,例如,使onPressed函数进入另一个方法.

build里面的代码:

class Btn extends HookConsumerWidget {
  const Btn({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isLoading = useState(false);
    final counter = ref.watch(counterProvider);
    final counterNotifier = ref.read(counterProvider.notifier);
    useEffect(() {
      if (isLoading.value) {
        Future.delayed(const Duration(seconds: 1), () {
          isLoading.value = false;
          counterNotifier.reset();
        });
      }
      return null;
    }, [isLoading.value]);

    return ElevatedButton.icon(
      onPressed: () => isLoading.value = true : null,
      icon: isLoading.value ? const CircularProgressIndicator() : Container(),
      label:Text(isLoading.value ? "Loading" : "$counter"),
    );
  }
}

我想把它变成:

class Btn extends HookConsumerWidget {
  const Btn({super.key});

  // declare isLoading

  void onPressed() {
    isLoading.value = true;
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final counter = ref.watch(counterProvider);
    final counterNotifier = ref.read(counterProvider.notifier);
    useEffect(() {
      if (isLoading.value) {
        Future.delayed(const Duration(seconds: 1), () {
          isLoading.value = false;
          counterNotifier.reset();
        });
      }
      return null;
    }, [isLoading.value]);

    return ElevatedButton.icon(
      onPressed: onPressed,
      icon: isLoading.value ? const CircularProgressIndicator() : Container(),
      label: Text(isLoading.value ? "Loading" : "$counter"),
    );
  }
}

推荐答案

你可以把你的类变成ConsumerStatefullWidget并丢弃钩子,然后所有的参数都可以变成类字段.

此外,尽量不要把逻辑拉到小部件中.有业务逻辑,然后把它放在通知类中(甚至使用包含数据、加载和错误的"密封"状态的AsyncNotifier).如果是ui逻辑,将其放在present类中也不错.

所有这些都将增加代码的可重用性,并允许应用程序的每一层都清楚地履行其职责.

Flutter相关问答推荐

当仅点击一行时,所有行都被选中

在Flutter中创建具有固定行的压缩水平列表

我如何才能动态地将小部件排成一排进行排列呢?

在Flutter 中创建自定义Snackbar类

Ffltter:发布版本中的Path NotFoundException

Flutter API请求BadState响应

Flutter 翼future 建造者不断开火和重建.它在每次重建时都会生成一个新的随机数--我如何防止这种情况?

如何将WebViewWidget和WillPopScope结合起来

Flutter如何将2个以上的值传递到ListView上的另一个屏幕?

如何将 Flutter 项目迁移到具有多个插件的 Gradle 8?

Flutter Riverpod 没有捕获 List 的嵌套值变化

即使小部件比Flutter 中的屏幕更宽,也始终显示滚动条

如何使Flutter 边框宽度在外面而不是在里面?

不使用 GlobalKey 仍然收到 GlobalKey 被多次使用的错误

Firebase Auth - 有没有办法为新用户预先生成 UID?

使用 riverpod 提供 GoRouter 实例的正确方法是什么?

Flutter中如何连续获取TextField的文本是否为空?

为什么 Flutter riverpod 直接分配不起作用但方法可以

在 Flutter 中,如何使用文本字段和方形图像进行行布局

Flutter Desktop,如何获取windows用户配置文件名称?