我正在调用初始方法以使用 initState 从 API 加载数据。但这导致我出错。这是错误:
Unhandled Exception: inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState.initState() completed.
When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget.
Run Code Online (Sandbox Code Playgroud)
我的代码是:
@override
void initState() {
super.initState();
this._getCategories();
}
void _getCategories() async {
AppRoutes.showLoader(context);
Map<String, dynamic> data = await apiPostCall(
apiName: API.addUser,
context: context,
parameterData: null,
showAlert: false,
);
if(data.isNotEmpty){
AppRoutes.dismissLoader(context);
print(data);
}else {
AppRoutes.dismissLoader(context);
}
}
Run Code Online (Sandbox Code Playgroud)
sie*_*ega 66
您需要_getCategories在initState完成后调用。
@override
void initState() {
super.initState();
Future.delayed(Duration.zero, () {
this._getCategories();
});
// Could do this in one line: Future.delayed(Duration.zero, this._getCategories);
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用其他答案中所示的addPostFrameCallback以不同的方式执行此操作。
Emi*_*gan 21
使用在 initState 之后调用的didChangeDependencies方法。
对于您的示例:
@override
void initState() {
super.initState();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
this._getCategories();
}
void _getCategories() async {
// Omitted for brevity
// ...
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*len 16
添加帧回调可能比使用Future.delayed零持续时间更好- 它对发生的事情更加明确和清晰,并且这种情况是帧回调的设计目的:
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
_getCategories();
});
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是把它放在PostFrameCallback中间initState,Build这样我们就可以确定它initState已经完成了。
@override
void initState() {
WidgetsBinding.instance.addPostFrameCallback((_) => getData());
super.initState();
}
getData() async {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16046 次 |
| 最近记录: |