我目前正在处理一个问题,我需要来自 API 的一些数据才能将其显示到我的小部件中。我遵循了一些 Provider 架构模式,在那里你 setState 两次:
1- 获取数据时
2- 当数据已经被获取时
所以我目前正在处理的问题是,我的小部件抛出以下错误:
setState() or markNeedsBuild() called during build.
我知道这个错误是因为在构建过程中调用了 setState,但是..如何在构建过程中获取我的 api,然后将它显示给我的小部件?这是我的代码:
NewsPage.dart
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
SideBarWidget _sidebar;
@override
void initState() {
Provider.of<HomeViewModel>(context, listen: false)
.fetchUltimaNoticia(context); --> ****Data to get fetched****
_sidebar = const SideBarWidget();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('INICIO'),
centerTitle: true,
automaticallyImplyLeading: false,
leading: Builder(
builder: (context) => …Run Code Online (Sandbox Code Playgroud)