How to correctly fetch APIs using Provider in Flutter


I’m currently dealing with a problem where I need some data from an API to show it into my widgets. I’ve following some Provider architecture pattern, where you setState two times:

1- When data is being fetched

2- When data is already fetched

So the problem I’m currently dealing is, my widget throws the following error:

setState() or markNeedsBuild() called during build.

I know this error is because setState is called during build, but.. how can I fetch my api during build, and then show it to my widgets? Here is my code:


    class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();

class _HomePageState extends State<HomePage> {
  SideBarWidget _sidebar;

  void initState() {
    Provider.of<HomeViewModel>(context, listen: false)
        .fetchUltimaNoticia(context); --> ****Data to get fetched****
    _sidebar = const SideBarWidget();

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('INICIO'),
        centerTitle: true,
        automaticallyImplyLeading: false,
        leading: Builder(
          builder: (context) => IconButton(
            icon: const Icon(,
            onPressed: () => Scaffold.of(context).openDrawer(),
      drawer: _sidebar,
      body: FormNoticiaContainer(),


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()


    class HomeViewModel extends BaseModel {

  NoticiaDB _noticia;

  NoticiaDB get noticia => _noticia;

  set setNoticia(NoticiaDB noticia) {
    _noticia = noticia;

  Future fetchUltimaNoticia(BuildContext context) async {

    var response = await noticiaProvider.obtenerNoticiaPublicada();

    setNoticia = response;



 ViewState _state = ViewState.Idle;

  ViewState get state => _state;

  void setState(ViewState viewState) {
    _state = viewState;


You can use WidgetsBinding.instance.addPostFrameCallback
For detail, you can reference

code snippet

void initState(){
    Provider.of<HomeViewModel>(context, listen: false)


Answered By – chunhunghan

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.