cant access variables in provider class from a different class in flutter

Issue

I have the classes below

class AppState with ChangeNotifier{
Set<Polyline> _polylines = Set<Polyline>();
LocationData _currentLocation;

Set<Polyline> get polylines => _polylines;
LocationData get currentLocation => _currentLocation;

}

in my main.dart I have

void main() => runApp(
    MultiProvider(

      providers: [
        ChangeNotifierProvider.value(value: AppState())
      ],
    child: MyApp()),
); 

Then I try to access it in a different class

...
@override
Widget build(BuildContext context) {
  final appState = Provider.of<AppState>(context);

appState.currentLocation != null?Container():Text()
}
...


But the problem is that I get the error that 
The getter 'currentLocation' isn't defined for the type 'AppState'.
Try importing the library that defines 'currentLocation', correcting the name to the name of an existing getter, or defining a getter or field named 'currentLocation'.

Cant seem to see what am doing wrong. how can I fix this

Solution

You should first create your ChangeNotifier using the default constructor, as stated in the official documentation.

Provider official documentation on Pub.dev

  • DO create a new ChangeNotifier inside create.
ChangeNotifierProvider(
  create: (_) => new MyChangeNotifier(),
  child: ...
)
  • DON’T use ChangeNotifierProvider.value to create your ChangeNotifier.
ChangeNotifierProvider.value(
  value: new MyChangeNotifier(),
  child: ...
)
  • DON’T create your ChangeNotifier from variables that can change over the time.

In such situation, your ChangeNotifier would never be updated when the value changes.

int count;

ChangeNotifierProvider(
  create: (_) => new MyChangeNotifier(count),
  child: ...
)

If you want to pass variables to your ChangeNotifier, consider using ChangeNotifierProxyProvider.


So your MultiProvider should look something like this:

void main() => runApp(
    MultiProvider(

      providers: [
        ChangeNotifierProvider(create: (context) =>  AppState())
      ],
    child: MyApp()),
); 

Answered By – Ayman Barghout

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.