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.
return _texts.toString();and called it through theCustomTextwidget.