Provider: Call provider function in initstate

Created on 31 Jul 2019  路  5Comments  路  Source: rrousselGit/provider

there is an issue when try to call provider function inside initState() method

I'm using it as the following:

@override

initState()
{
  super.initState();

  Provider.of<DataProvider>(context, listen: false).getData();

} 

the error log is:

I/flutter (15687):   * Ensure the Provider<DataProvider> is an ancestor to this MyHomePage Widget
I/flutter (15687):   * Provide types to Provider<DataProvider>
I/flutter (15687):   * Provide types to Consumer<DataProvider>
I/flutter (15687):   * Provide types to Provider.of<DataProvider>()
I/flutter (15687):   * Always use package imports. Ex: `import 'package:my_app/my_code.dart';
I/flutter (15687):   * Ensure the correct `context` is being used.
I/flutter (15687):
I/flutter (15687): If none of these solutions work, please file a bug at:
I/flutter (15687): https://github.com/rrousselGit/provider/issues

can you look into the issue, i've added listen: false but still show error.

Thanks

Most helpful comment

For anyone who is reading this thread and still doesn't know what to do here is a great explanation: https://pub.dev/packages/provider#faq and the first question:

I have an exception when obtaining Providers inside initState. What can I do?

All 5 comments

Have you tried doing what the error suggests?
This is an error on your end. You likely forgot to add a provider, or inserted it in the wrong place.

this is my full code:

main.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_data_app/Provider/DataProvider.dart';
import 'package:provider_data_app/mainUI.dart';




void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );


  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);


  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


@override
initState()
{
  super.initState();
 Provider.of<DataProvider>(context, listen: false).getData();


} 



  @override
  Widget build(BuildContext context) {

    return  ChangeNotifierProvider(

          builder: (_) => DataProvider(),

          child: MainUI()
          );





  }










}

MainUI.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:provider_data_app/Provider/DataProvider.dart';


class MainUI extends StatelessWidget {



  @override
  Widget build(BuildContext context) {



return Scaffold(
      appBar: AppBar(

        title: Text('provider app'),
      ),
      body: Center(

        child:  Consumer<DataProvider>(
  builder: (context, dataProvider, child) {

      return dataProvider.isBusy? Text('busy') :  Text(dataProvider.dbVersion);

  }
        )


      ),
      floatingActionButton: FloatingActionButton(
        //listen false to rebuild only inside Consumer not full widget
       onPressed:()=> Provider.of<DataProvider>(context,listen: false).getData(),
        tooltip: 'Increment',
        child: Icon(Icons.add),


      )



    );

  }
}

DataProvider.dart

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';



class DataProvider with ChangeNotifier {
  String _dbVersion = '';
  String get dbVersion => _dbVersion;

  bool _isBusy=false;
  bool get isBusy => _isBusy;



  set isBusy(bool value)
  {
      _isBusy=value;
      notifyListeners();
  }

  Future<void> getData() async{



          isBusy=true;

          _dbVersion=await getDbVersion();



          isBusy=false;






}




  Future<String> getDbVersion() async {
   return '2.2.0';
   }






}



i don't know why Provider.of(context, listen: false).getData(); not working in initstate and give me an error

@rrousselGit gave the answer, you're inserting it in the wrong place. Your initState is calling a function on a Provider that hasn't been built yet. You need to create the provider and then call that function later down the widget tree in a different initstate.

Try to setup your ChangeNotifierProvider before MaterialApp.

For anyone who is reading this thread and still doesn't know what to do here is a great explanation: https://pub.dev/packages/provider#faq and the first question:

I have an exception when obtaining Providers inside initState. What can I do?

Was this page helpful?
0 / 5 - 0 ratings