initState method
Called when this object is inserted into the tree.
The framework will call this method exactly once for each State object it creates.
Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).
If a State's build method depends on an object that can itself change state, for example a ChangeNotifier or Stream, or some other object to which one can subscribe to receive notifications, then be sure to subscribe and unsubscribe properly in initState, didUpdateWidget, and dispose:
- In initState, subscribe to the object.
- In didUpdateWidget unsubscribe from the old object and subscribe to the new one if the updated widget configuration requires replacing the object.
- In dispose, unsubscribe from the object.
You should not use BuildContext.dependOnInheritedWidgetOfExactType from this method. However, didChangeDependencies will be called immediately following this method, and BuildContext.dependOnInheritedWidgetOfExactType can be used there.
Implementations of this method should start with a call to the inherited
method, as in super.initState().
Implementation
@override
void initState() {
super.initState();
widget.inputController?.bind(this);
inlineStyle = widget.inline;
_focusNode = widget.focusNode ?? FocusNode();
_focusNode.addListener(() {
final hasFocus = _focusNode.hasFocus;
widget.focusListener?.call(context, hasFocus);
// 当获得焦点且配置了 buildPop 时显示弹出层
if (hasFocus && widget.buildPop != null && widget.onFocusShowPop) {
addPop();
return;
}
// 失去焦点时延迟关闭弹出层,给按钮点击事件足够的时间执行
// 这是关键:延迟时间要足够长,让点击事件先完成
if (!hasFocus && _overlayEntry != null) {
Future.delayed(const Duration(milliseconds: 200), () {
// 再次检查焦点状态和 overlay 是否还存在
if (!_focusNode.hasFocus && _overlayEntry != null && mounted) {
removePop();
}
});
}
});
}