首页 > 解决方案 > 父小部件不使用继承更新

问题描述

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. 为什么呢?

标签: flutterdart

解决方案


在构建 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),
      ),
    );
  }
}

推荐阅读