Flutter 中,didUpdateWidget() 方法用于处理与父 widget 相关的更新。当父 widget 重建并向当前 widget 传递新的配置(即新的 widget 实例)时,didUpdateWidget() 会被调用。以下是一个简单的示例,演示了如何在一个自定义 StatefulWidget 中使用 didUpdateWidget() 来检测 widget 属性的变化,并相应地做出反应。

只要在父widget中调用setState(哪怕是空的),子widgetdidUpdateWidget就一定会被调用,不管父widget传递给子widget构造方法的参数有没有改变。

只要didUpdateWidget被调用,接来下build方法就一定会被调用。

示例说明

假设有一个简单的 CounterWidget,它接受一个 count 值。我们希望每次父 widget 更新这个 count 值时,CounterWidget 都能通过 didUpdateWidget() 捕捉到这个变化并打印出相关信息。

Step 1: 创建一个名为 CounterWidget 的 StatefulWidget

class CounterWidget extends StatefulWidget {
  final int count;

  const CounterWidget({super.key, required this.count});

  @override
  State<CounterWidget> createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  @override
  Widget build(BuildContext context) {
    print('3、子组件 build 方法执行');
    return Container(
      padding: EdgeInsets.all(20),
      child: Text('Count: ${widget.count}', style: TextStyle(fontSize: 24)),
    );
  }

  @override
  void didUpdateWidget(covariant CounterWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print('1、子组件 didUpdateWidget 方法执行');
    if (oldWidget.count != widget.count) {
      // 这里可以添加一些逻辑来处理计数器更新
      print('2、Counter updated from ${oldWidget.count} to ${widget.count}');
    }
  }
}

Step 2: 在父 Widget 中使用 CounterWidget


// ignore: camel_case_types
class otherDemoIndexRoute extends StatefulWidget {
  const otherDemoIndexRoute({super.key});

  @override
  State<otherDemoIndexRoute> createState() => _otherDemoIndexRouteState();
}

// ignore: camel_case_types
class _otherDemoIndexRouteState extends State<otherDemoIndexRoute> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('无StreamController的Stream示例')),
      body: Column(
        children: [
          /// 使用 CounterWidget 组件(哪怕 _counter 不变,子组件 CounterWidget 的didUpdateWidget也会执行)
          CounterWidget(count: _counter),
          ElevatedButton(
            onPressed: () {
              setState(() {
                /// 即使没有方法体,只要调用了 setState,当前组件就会重新构建。
                _counter++;
              });
            },
            child: Text('++'),
          ),
        ],
      ),
    );
  }
}

总结:示例展示了如何使用 didUpdateWidget() 捕捉到父 widget 传递的新属性值,并可以在这个方法内部执行一些特定的逻辑,如更新状态、重新配置资源、发起网络请求、更新数据库或打印调试信息。这种方法在处理动态数据时非常有用,特别是在需要响应来自父 widget 属性变化的情况下。

didUpdateWidget 在以下情况下非常有用:

  1. 父组件更新时需要对子组件的状态进行同步或调整。
  2. 可以根据新的 Widget 配置执行一些副作用操作,如发起请求等。
  3. 它能让你有效地管理子组件与父组件之间的状态变化,避免不必要的重构和逻辑错误。

qngyun1029
980 声望15 粉丝