首页 > 解决方案 > 无法从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'.

似乎看不到做错了什么。我怎样才能解决这个问题

标签: flutterdartflutter-provider

解决方案


ChangeNotifier如官方文档中所述,您应该首先使用默认构造函数创建您的。

Pub.dev 上的提供者官方文档

  • 请在 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()),
); 

推荐阅读