我目前正在处理一个问题,我需要一些API中的数据才能将其显示在我的小部件中。我遵循了一些提供程序体系结构模式,其中两次setState:
1-提取数据时
2-当数据已被提取
所以我当前要解决的问题是,我的小部件引发以下错误:
StudentId-Monday-Tuesday-Wednesday-Thursday-Friday-Saturday-Sunday
2374 - 0 - 1 - 0 - 1 - 0 - 0 - 0
我知道此错误是因为在构建过程中调用了setState,但是..如何在构建过程中获取我的api,然后将其显示给我的小部件?这是我的代码:
NewsPage.dart
setState() or markNeedsBuild() called during build.
FormContainer()
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) => IconButton(
icon: const Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
),
drawer: _sidebar,
body: FormNoticiaContainer(),
);
}
}
HomeViewModel.dart
Widget build(BuildContext context) {
return _crearBodyNoticia(context);
}
Widget _crearBodyNoticia(context) {
final homeVm = Provider.of<HomeViewModel>(context, listen: true);
return homeVm.state == ViewState.Busy
? Center(child: CircularLoading())
: Center(
child: DataToShowWidget()
BaseModel
class HomeViewModel extends BaseModel {
////////
//NOTICIAS
////////
NoticiaDB _noticia;
NoticiaDB get noticia => _noticia;
set setNoticia(NoticiaDB noticia) {
_noticia = noticia;
}
Future fetchUltimaNoticia(BuildContext context) async {
setState(ViewState.Busy);
var response = await noticiaProvider.obtenerNoticiaPublicada();
setNoticia = response;
setState(ViewState.Idle);
}
}
答案 0 :(得分:8)
您可以使用WidgetsBinding.instance.addPostFrameCallback
有关详细信息,您可以参考https://www.didierboelens.com/faq/week2/
代码段
@override
void initState(){
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
Provider.of<HomeViewModel>(context, listen: false)
.fetchUltimaNoticia(context);
});
}