flutter - 无法从flutter中的不同类访问提供者类中的变量
问题描述
我有以下课程
class AppState with ChangeNotifier{
Set<Polyline> _polylines = Set<Polyline>();
LocationData _currentLocation;
Set<Polyline> get polylines => _polylines;
LocationData get currentLocation => _currentLocation;
}
在我的 main.dart 我有
void main() => runApp(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: AppState())
],
child: MyApp()),
);
然后我尝试在不同的类中访问它
...
@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'.
似乎看不到做错了什么。我怎样才能解决这个问题
解决方案
ChangeNotifier
如官方文档中所述,您应该首先使用默认构造函数创建您的。
- 请在 create 中创建一个新的 ChangeNotifier。
ChangeNotifierProvider(
create: (_) => new MyChangeNotifier(),
child: ...
)
- 不要使用 ChangeNotifierProvider.value 来创建您的 ChangeNotifier。
ChangeNotifierProvider.value(
value: new MyChangeNotifier(),
child: ...
)
- 不要从随时间变化的变量创建您的 ChangeNotifier。
在这种情况下,当值更改时,您的 ChangeNotifier 将永远不会更新。
int count;
ChangeNotifierProvider(
create: (_) => new MyChangeNotifier(count),
child: ...
)
如果要将变量传递给 ChangeNotifier,请考虑使用 ChangeNotifierProxyProvider。
所以你MultiProvider
应该看起来像这样:
void main() => runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => AppState())
],
child: MyApp()),
);
推荐阅读
- javascript - 如何在 vue 中添加 eventlistener 并访问 this.$refs 中的组件
- javascript - 在执行 POST 功能之前导致页面重新加载的点击事件
- python - 使用附加列表python循环
- ruby - Rails 6自动加载未找到类
- reactjs - 如何在 react-native (expo) 应用程序中使用 OTA 更新?
- javascript - Angular 将图像上传为多部分表单数据(NestJS 后端)
- ios - 如何避免这些约束错误?
- amazon-web-services - 如何从 Django 中的 S3 存储桶下载媒体文件
- iot - 无法将在 Watson IoT 中设置的设备凭证添加到您的 IoT 设备
- ruby-on-rails - Heroku 上的 Ruby on Rails 应用程序在启动时崩溃