我有以下类(class)
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
。
Provider official documentation on Pub.dev
ChangeNotifierProvider(
create: (_) => new MyChangeNotifier(),
child: ...
)
ChangeNotifierProvider.value(
value: new MyChangeNotifier(),
child: ...
)
在这种情况下,值更改时将永远不会更新您的ChangeNotifier。
int count;
ChangeNotifierProvider(
create: (_) => new MyChangeNotifier(count),
child: ...
)
如果要将变量传递给ChangeNotifier,请考虑使用ChangeNotifierProxyProvider。
因此,您的
MultiProvider
应该如下所示:void main() => runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => AppState())
],
child: MyApp()),
);