简体   繁体   中英

Flutter Provider: Why does this error happens when calling Provider.of<Widget>(context) like tihis:

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM