【问题标题】:Flutter Provider: Why does this error happens when calling Provider.of<Widget>(context) like tihis:Flutter Provider:为什么在调用 Provider.of<Widget>(context) 时会出现此错误,如 tihis:
【发布时间】:2020-02-19 12:00:33
【问题描述】:

我是 Flutter 的新手,我正在测试 Provider,但不知道为什么这样做会起作用(我的意思是它在 appbar 中显示一个列表):

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

使用几乎什么都不做的 CustomText 类:

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

但是这件事抛出了一个 - 无法在这个 MyApp 小部件上方找到正确的提供者 - 错误:

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()),
          ),
        ),
      ),
    );
  }
}

数据类是:

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();
  }
}

我只是看不出有什么区别或为什么重要。该代码不应该是等效的吗?任何见解将不胜感激。

【问题讨论】:

  • 那是因为你仍在返回一个列表。您可以将其更改为return _texts.toString(); 并通过CustomText 小部件调用它。
  • 它返回 alit 的事实并不重要。

标签: flutter dart


【解决方案1】:

不同之处在于,在CustomText 的情况下,context 来自其父小部件MyApp,而在第二种情况下,context 来自MyApp 的父小部件。由于你的Provider是在MyApp内部实现的,所以如果你使用MyApp的父级的context(第二种情况),它就找不到提供者了

【讨论】:

  • 谢谢。你是对的,我将 ChangeNotifierProvider 移到了 runApp 函数中,它起作用了。
猜你喜欢
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
相关资源
最近更新 更多