[英]Using more than one provider in a flutter app
I have started using PROVIDER to manage state in my app.我已经开始使用 PROVIDER 在我的应用程序中管理 state。 I followed tutorials and wrapped my Material app with ChangeNotifierProvider.我遵循教程并使用 ChangeNotifierProvider 包装了我的 Material 应用程序。 Here's the code:这是代码:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (BuildContext context) => ListsProvider(),
child: MaterialApp(
title: 'WordsApp',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: StartingPage.id,
routes: {
StartingPage.id: (context) => StartingPage(),
RegistrationScreen.id: (context) => RegistrationScreen(),
},
),
);
}
}
This provider called "ListsProvider" takes care of "providing" lists that need to be displayed on different screens.这个名为“ListsProvider”的提供者负责“提供”需要在不同屏幕上显示的列表。 I have now created a second provider which I called "user_data_provider" and I now need to add it to my app too.我现在创建了第二个提供程序,我称之为“user_data_provider”,现在我也需要将它添加到我的应用程序中。 It will take care of providing user data to many different screens.它将负责向许多不同的屏幕提供用户数据。
How can I do that?我怎样才能做到这一点?
To achive this you can use Multiprovider
as shown below要实现这一点,您可以使用Multiprovider
,如下所示
Add this to the top of your app.将此添加到您的应用程序的顶部。 If you need these obj everywhere.如果你到处都需要这些 obj。
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<user_data_provider>(
create: (_) => user_data_provider(),
),
ChangeNotifierProvider<ListsProvider>(
create: (_) => ListsProvider(),
),
],
child: Builder(
builder: (BuildContext context) {
return MaterialApp(
//YOur code goes here
);
},
),
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.