从其他函数 Flutter Hook Widget 传递和更新状态值

问题描述

我是 Flutter 钩子的新手,我有一个要求,我必须使用 HookWidget 而不是 StatefulWidget。据我所知,useState 只能在 build 函数中声明。

Widget build(BuildContext context) {
    final selectedBook = useState("");
    return Container(
       child: _buildBookListContainer(context)
    )  
}

Widget _buildBookListContainer(BuildContext context) {
  //I will want to update the state value or read the state value in the child function
  //how do I do that?
  //Example: selectedBook.value = "xxx";
}

我尝试将状态值作为函数参数传递,但它不起作用。我可以知道所有 HookWidget 类都会在构建函数中编写所有组件而无需折射吗?

解决方法

假设您使用的是 Riverpod,请在 https://www.youtube.com/watch?v=0lPzFS5CAPs 观看我相对简短的“使用我的 riverpod 入门套件从头开始构建计数器应用程序”。它展示了如何创建 StateProvider,然后引用它(使用监听)或更新它(不监听)以精确控制小部件重建。

相关问答

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