簡體   English   中英

Flutter - 如何使用多個 ChangeNotifierProvider 的

[英]Flutter - How to use multiple ChangeNotifierProvider's

我是 flutter 的新手,我試圖弄清楚如何在main.dart class 中使用多個 ChangeNotifierProvider

我已經為此苦苦掙扎了好幾個小時,但我似乎無法讓它發揮作用。

多個 ChangeNotifierProvider 用於 Auth Screen 和 Theme Changer。

void main() async {
  var delegate = await LocalizationDelegate.create(
      fallbackLocale: 'en_US', supportedLocales: ['en_US', 'sv']);

  runApp(LocalizedApp(delegate, MyApp()));
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<ThemeChanger>(context);
    var localizationDelegate = LocalizedApp.of(context).delegate;

    FlutterStatusbarcolor.setStatusBarWhiteForeground(false);

    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(
          value: Auth(),
        ),

        ChangeNotifierProvider<ThemeChanger>(
          create: (_) => ThemeChanger(CustomThemes.lightTheme.copyWith(
              textTheme:
                  CustomThemes.textTheme(CustomThemes.lightTheme.textTheme))),

          child: MaterialAppWithTheme(),
        )
      ],

      child: Consumer<Auth>(
        builder: (ctx, auth, _) => MaterialApp(
          title: translate('appbar.title_app'),
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            localizationDelegate
          ],
          supportedLocales: localizationDelegate.supportedLocales,
          locale: localizationDelegate.currentLocale,
          theme: theme.getTheme(),
          color: Theme.of(context).primaryColor,
          home: auth.isAuth ? MdDrawer(title: AppStrings.appTitle) : AuthenticationScreen(),
        ),
      ),
    );
  }
}

class MaterialAppWithTheme extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<ThemeChanger>(context);

    return MaterialApp(
      title: AppStrings.appTitle,
      debugShowCheckedModeBanner: false,
      theme: theme.getTheme(),
      color: Theme.of(context).primaryColor,
      home: MdDrawer(title: AppStrings.appTitle),
    );
  }
}

僅當小部件由提供者包裝或者是由該提供者包裝的小部件的子時,您才能在小部件中使用 object 的提供者。 這就是將您的提供程序放在小部件樹頂部的意思。

在這里,您使用了小部件內的 MultiProvider 和final theme = Provider.of<ThemeChanger>(context); 位於未由提供程序包裝的小部件部分中。

因此,不要直接使用theme: Provider.of<ThemeChanger>(context).getTheme();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM