gpt4 book ai didi

flutter - 未处理的异常 : inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState. initState() 已完成

转载 作者:IT王子 更新时间:2023-10-29 07:18:58 25 4
gpt4 key购买 nike

我正在调用初始方法以使用 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.

我的代码是:

@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);
}
}

最佳答案

您需要在 initState 完成后调用 _getCategories


@override
void initState() {
super.initState();

Future.delayed(Duration.zero, () {
this._getCategories();
});

// Could do this in one line: Future.delayed(Duration.zero, this._getCategories);
}

此外,您可以使用 addPostFrameCallback 以不同的方式执行此操作.为了使这项任务更容易,您可以创建一个 mixin 以添加到 StatefulWidgets。

mixin PostFrameMixin<T extends StatefulWidget> on State<T> {
void postFrame(void Function() callback) =>
WidgetsBinding.instance?.addPostFrameCallback(
(_) {
// Execute callback if page is mounted
if (mounted) callback();
},
);
}

然后,你只需要将这个 mixin 插入你的页面,就像这样:

class _MyPageState extends State<MyPage> with PostFrameMixin {
@override
void initState() {
super.initState();

postFrame(_getCategories);
}
}

关于flutter - 未处理的异常 : inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before _ScreenState. initState() 已完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56395081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com