title: How to update the state(Provider state) inside the initState function in Flutter?
body: <p>I want to fetch data from an API and set those data to the central state(provider) after creating a screen.( similar scenario of react useEfect function) </p>
  
  <pre><code>class MyApp2 extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return ChangeNotifierProvider&lt;Counter&gt;(
          child: MyHomePage(title: 'Flutter Demo Home Page'),
          create: (BuildContext context) =&gt; Counter());
    }
  }
      class _MyHomePageState extends State&lt;MyHomePage&gt; {
    void _incrementCounter(dynamic count) {
      count.incrementCounter();
    }
  
    int fetchData() {
      //api request code
      return data; // return fetched data
    }
  
    @override
    Widget build(BuildContext context) {
      final count = Provider.of&lt;Counter&gt;(context);
  
      count.setCounter(fetchData());
  
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: &lt;Widget&gt;[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '${count.counter}',
                style: Theme.of(context).textTheme.display1,
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () =&gt; _incrementCounter(count),
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      );
    }
  }
  
  class Counter with ChangeNotifier{
    int counter= 0;
  
    void setCounter(int x){
      counter =x;
      notifyListeners();
    }
  
    void clearCounter(){
      counter =0;
      notifyListeners();
    }
    void incrementCounter(){
      counter++;
      notifyListeners();
    }
  }
  </code></pre>
  
  <p>It throws and exception and it doesn't work. </p>
  
  <pre><code>setState() or markNeedsBuild() called during build. 
  </code></pre>
  
  <p>If I remove the notifyListeners() function, the app runs without any exceptions but the widget what I want to rebuild isn't rebuilt. </p>
  
  <pre><code>void setCounter(int x){
      counter =x;
     // notifyListeners();
    }
  </code></pre>
  
  <p>What is the best way to do that?</p>