【发布时间】:2021-07-18 10:34:02
【问题描述】:
我正在开发送餐应用程序,并且正在使用 Provider 作为状态管理架构。问题是当我向我的应用程序添加第二个提供程序时,它给出了错误。
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MultiProvider(
providers: [
ChangeNotifierProvider<GPSViewModel>(create: (_) => GPSViewModel()),
ChangeNotifierProvider<OTPViewModel>(create: (_) => OTPViewModel()),
],
child: GPS(),
),
);
}
错误是
Error: Could not find the correct Provider<OTPViewModel> above this MobileOTP Widget
在 MobileOTP 中,我在 init 状态方法中像这样访问提供程序
@override
void initState() {
super.initState();
Provider.of<OTPViewModel>(context, listen: false).
verifyMobileNumber(widget.phone,verificationCompleted,verificationFailed,codeSent,codeAutoRetrievalTimeout);
}
完整的错误跟踪是这样的
Error: Could not find the correct Provider<OTPViewModel> above this MobileOTP Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that MobileOTP is under your MultiProvider/Provider<OTPViewModel>.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
```
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
```
consider using `builder` like so:
```
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
What i am doing wrong ?
【问题讨论】:
标签: flutter flutter-dependencies flutter-provider