flutter - 父小部件不使用继承更新
问题描述
ParentPage
:
class ParentPage extends StatefulWidget {
@override
ParentPageState createState() => ParentPageState();
}
class ParentPageState<T extends ParentPage> extends State<T> {
int counter = 0;
void incrementCounter() => setState(() => counter++);
@override
Widget build(BuildContext context) => Text('$counter'); // Not updating
}
ChildPage
:
class ChildPage extends ParentPage {
@override
_ChildPageState createState() => _ChildPageState();
}
class _ChildPageState extends ParentPageState<ChildPage> {
@override
Widget build(BuildContext context) {
print('build[$counter]'); // Updates
return Scaffold(
body: ParentPage(),
floatingActionButton: FloatingActionButton(
onPressed: incrementCounter,
child: Icon(Icons.add),
),
);
}
}
我home: ChildPage()
在我的MaterialApp
小部件中使用。
问题:
当我单击 FAB 时,它会增加counter
(可以在_ChildPageState.build
方法的 print 语句中看到),但中的Text
小部件ParentPage
保持在0
. 为什么呢?
解决方案
在构建 ChildPage 时,您会创建 ParentPage 的新实例。
body: ParentPage(),
那是一个单独的实例,所以它有自己的状态。
只是如果您有例如 2 个不同的容器 - 您不会仅仅因为它们使用相同的类而期望它们具有相同的属性。
您可以通过检查counter
子小部件中的值来测试它。
class ChildPage extends ParentPage {
@override
_ChildPageState createState() => _ChildPageState();
}
class _ChildPageState extends ParentPageState<ChildPage> {
@override
Widget build(BuildContext context) {
print('build[$counter]'); // Updates
return Scaffold(
body: Column(children: [ParentPage(), Text('$counter'),]),
floatingActionButton: FloatingActionButton(
onPressed: incrementCounter,
child: Icon(Icons.add),
),
);
}
}
推荐阅读
- javascript - 如何将它包装在 setTimeout 中?如果我们假设从服务器接收数据需要时间(这里只是 txt 文件),所以在一段时间后执行它
- c# - 获取 IEnumerable 的属性
(其中 T 是对象) - autodesk-forge - 在 BIM360 OSS 中为对象创建签名 URL
- qt - Qt 5中具有相同字体点大小的不同实际字体大小
- python - 使用python从验证码图像中删除行
- python - Python计算直到当前行的总计
- c++ - How to put some inputs inside one bitmask? #arduino
- c# - c#UTF8 GetString从字节数组不等于php chr函数
- hibernate - hibernate 如何确保会话缓存或一级缓存使用数据库中的最新数据进行更新?
- java - 以函数式 Java 计算阶乘递归