1

I'm new to flutter and I'm testing Provider and can't figure out why doing this works (by work i mean it shows a list in the appbar):

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider<Data>( builder: (context)=> Data(), child: MaterialApp( home: Scaffold( appBar: AppBar( title: CustomText(), ), ), ), ); } } 

With a CustomText class that does practically nothing:

class CustomText extends StatelessWidget{ @override Widget build(BuildContext context) { return Text(Provider.of<Data>(context).texts.tostring()); } } 

But this other thing throws a - Could not find the correct Provider above this MyApp Widget - Error:

class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return ChangeNotifierProvider<Data>( builder: (context)=> Data(), child: MaterialApp( home: Scaffold( appBar: AppBar( title: Text(Provider.of<Data>(context).texts.toString()), ), ), ), ); } } 

The Data class is :

class Data with ChangeNotifier{ List<String> _texts = ['Text 1', 'Text 2', 'Text 3', 'Text 4',]; get texts { return _texts; } void deleteText(int index){ this._texts.removeAt(index); notifyListeners(); } void addText(String text){ this._texts.add(text); notifyListeners(); } } 

I just can not see what is the difference or why that matters. Shouldn't that code be equivalent? Any insight will be much appreciated.

2
  • That is because you're still returning a List. You could change it into return _texts.toString(); and called it through the CustomText widget. Commented Oct 23, 2019 at 9:56
  • The fact that it is returning alit does not matter whatsoever. Commented Oct 23, 2019 at 17:19

1 Answer 1

1

The difference is that in the CustomText case, context is from its parent widget which is MyApp, whereas in the second case, context is from MyApp's parent. Since your Provider is implemented inside MyApp, it cannot find the provider if you use MyApp's parent's context (the second case)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. You are right, I moved the ChangeNotifierProvider to the runApp function and it worked.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.