在此联系人页面小部件上方找不到正确的提供程序<...>



我正在尝试与Flutter和我试图建立一个简单的应用程序使用提供商模式

我的问题

我正在尝试访问一个小部件中的提供程序,一旦我在有状态小部件类中获得所需的提供程序,我就会得到此错误。我不知道我哪里做错了。

误差

Error: Could not find the correct Provider<ContactProvider> above this ContactsPage 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 ContactsPage is under your MultiProvider/Provider<ContactProvider>.
This usually happens when you are creating a provider and trying to read it immediately.
...

main.dart

import 'package:ProvidersExample/provider_list.dart';
void main() async => runApp(Home());

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: providerList,
child: MaterialApp(
home: ContactsPage(),
)
);
}
}

providers_list.dart

List<SingleChildWidget> providerList = [
ChangeNotifierProvider(
create: (_) => ContactProvider(),
lazy: false,
)
];

提供者:contact_provider.dart

class ContactProvider extends ChangeNotifier{
List<Contact> _contactList = [];
// getter
List<Contact> get contacts {
return [..._contactList];
}
// setter
set contacts(List<Contact> newContacts) {
_contactList = newContacts;
notifyListeners();
}
...

小部件contacts_page.dart

class ContactsPage extends StatefulWidget {
@override
_ContactsPageState createState() => _ContactsPageState();
}
class _ContactsPageState extends State<ContactsPage> {
@override
void initState(){
super.initState();
}
@override
Widget build(BuildContext context) {
// This line throws the error
ContactProvider _provider = Provider.of<ContactProvider>
(context, listen:false);
return Scaffold(
appBar: AppBar(
title: Text(
...

我认为原因是您引用了在provider_list.dart外部创建的提供商列表,该列表无法从您的小部件树访问您的上下文。

试试这个:

List providerList(context) {
return [
ChangeNotifierProvider(
create: (context) => ContactProvider(),
lazy: false,
)
];
}

providerList()现在是一个接受context的方法,并使用该上下文来注册您的提供者,并返回它。

您应该在创建提供程序时指定类型<T>,以便它知道您在小部件树中寻找哪种类型。

List<SingleChildWidget> providerList = [
ChangeNotifierProvider<ContactProvider>(
create: (_) => ContactProvider(),
lazy: false,
)
];

相关内容

  • 没有找到相关文章

最新更新