initState() 在将新的 Widget 插入树时调用。
框架将为每个 [State] 对象仅调用一次此方法
它创建。这将被调用一次,因此执行只需要执行一次的工作,但请记住 context 不能在此处使用,因为小部件状态仅加载 initState() 工作已完成。
语法:
@override
void initState() {
debugPrint('initState()');
super.initState();
}
didChangeDependencies() 在此 [State] 对象的依赖项发生更改时调用。
那么,究竟它是如何被调用的? 根据上面的定义,看起来它会在状态改变后被调用,但我们是如何知道状态改变的呢?
示例:
以下示例使用Provider 状态管理机制从父小部件更新子小部件。 Provider 有一个名为 updateShouldNotify 的属性,它决定是否更改状态。如果它返回true,那么只有didChangeDependencies 在ChildWidget 类中被调用。
updateShouldNotify 默认在内部返回 true,因为它知道状态已更改。 那为什么我们需要 updateShouldNotify? 之所以需要,是因为如果有人想在特定条件下更新状态,
例如:如果 UI 需要仅显示 even 值,那么我们可以添加类似的条件
updateShouldNotify: (oldValue, newValue) => newValue % 2 == 0,
代码片段:
class ParentWidget extends StatefulWidget {
ParentWidget({Key key, this.title}) : super(key: key);
final String title;
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Life Cycle'),
),
body: Provider.value(
value: _counter,
updateShouldNotify: (oldValue, newValue) => true,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Press Fab button to increase counter:',
),
ChildWidget()
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class ChildWidget extends StatefulWidget {
@override
_ChildWidgetState createState() => _ChildWidgetState();
}
class _ChildWidgetState extends State<ChildWidget> {
int _counter = 0;
@override
void initState() {
print('initState(), counter = $_counter');
super.initState();
}
@override
void didChangeDependencies() {
_counter = Provider.of<int>(context);
print('didChangeDependencies(), counter = $_counter');
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
print('build(), counter = $_counter');
return Text(
'$_counter',
);
}
}
输出日志:
I/flutter ( 3779): didChangeDependencies(), counter = 1
I/flutter ( 3779): build(), counter = 1
详细说明:
https://medium.com/@jitsm555/differentiate-between-didchangedependencies-and-initstate-f98a8ae43164?sk=47b8dda310f307865d8d3873966a9f4f