【问题标题】:I want make able to change dark/light mode with Switch at DrawerHeader我希望能够使用 DrawerHeader 处的 Switch 更改暗/亮模式
【发布时间】:2020-11-15 20:11:25
【问题描述】:

我希望能够使用 DrawerHeader 处的 Switch 更改暗/亮模式。但我遇到了一个错误。

错误:在此消费者小部件上方找不到正确的提供者 这可能是因为您使用了不包含提供程序的BuildContext 你的选择。有几种常见的情况:

  • 您尝试读取的提供程序位于不同的路径中。 提供者是“范围的”。因此,如果您在路线内插入提供者,那么 其他路由将无法访问该提供商。
  • 您使用了BuildContext,它是您尝试读取的提供程序的祖先。 确保 Consumer 在您的 MultiProvider/Provider 下。 这通常发生在您创建提供程序并尝试立即读取它时。

anasayfa.dart

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ThemeNotifier>(
      create: (_) => ThemeNotifier(),
      child: Consumer<ThemeNotifier>(
        builder: (context, ThemeNotifier notifier, child) {
          return MaterialApp(
            title: 'Flutter Theme Provider',
            theme: notifier.darkTheme ? dark : light,
            home: Anasayfa(),
          );
        },
      ),
    );
  }
}

class Anasayfa extends StatefulWidget {
  @override
  _AnasayfaState createState() => _AnasayfaState();
}

class _AnasayfaState extends State<Anasayfa> {
  int currentPage = 0;

  nested() {
    return NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverAppBar(
              toolbarHeight: 40,
              expandedHeight: 92.0,
              floating: false,
              pinned: true,
              flexibleSpace: FlexibleSpaceBar(
                background: Image.asset(
                  "assets/images/besmele.jpg",
                  fit: BoxFit.cover,
                ),
              ),
              actions: [
                IconButton(
                  icon: Icon(Icons.account_circle),
                  color: Colors.white,
                  onPressed: () {},
                ),
              ],
            )
          ];
        },
        body: Container());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: nested(),
      drawer: Drawer(
        child: DrawerDosyasi(),
      ),
      bottomNavigationBar: CurvedNavigationBar(
        color: Colors.blue,
        backgroundColor: Colors.white,
        buttonBackgroundColor: Colors.blue,
        height: 50,
        items: <Widget>[
          Icon(
            Icons.campaign,
            size: 20,
            color: Colors.white,
          ),
          Icon(
            Icons.supervisor_account,
            size: 20,
            color: Colors.white,
          ),
          Icon(
            Icons.home,
            size: 20,
            color: Colors.white,
          ),
          Icon(
            Icons.video_collection_rounded,
            size: 20,
            color: Colors.white,
          ),
          Icon(
            Icons.menu_book_rounded,
            size: 20,
            color: Colors.white,
          ),
        ],
        animationDuration: Duration(
          milliseconds: 300,
        ),
        index: 2,
        animationCurve: Curves.bounceInOut,
        onTap: (index) {
          debugPrint("Current index is $index");
        },
      ),
    );
  }
}

drawerDosyasi.dart

class DrawerDosyasi extends StatefulWidget {
  @override
  _DrawerDosyasiState createState() => _DrawerDosyasiState();
}

class _DrawerDosyasiState extends State<DrawerDosyasi> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
            child: Row(
              children: [
                Expanded(
                  flex: 1,
                  child: Consumer<ThemeNotifier>(
                    builder: (context, notifier, child) => Switch(
                      onChanged: (val) {
                        notifier.toggleTheme();
                      },
                      value: notifier.darkTheme,
                    ),
                  ),
                ),
                Expanded(
                  flex: 3,
                  child: CircleAvatar(
                    radius: 60,
                    backgroundColor: Colors.white,
                  ),
                ),
                Expanded(flex: 1, child: SizedBox.expand()),
              ],
            ),
          ),
          ListTile(
            leading: Icon(Icons.home),
            title: Text('Anasayfa'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.account_circle),
            title: Text('Profil'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.campaign),
            title: Text('Duyurular'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.account_box),
            title: Text('Hocalar'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.library_books),
            title: Text('Dergiler'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.video_collection_rounded),
            title: Text('Canlı Dersler'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.menu_book_rounded),
            title: Text('Kütüphane'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.supervisor_account),
            title: Text('Tartışmalar'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.create),
            title: Text('Yazı Gönder'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.message_rounded),
            title: Text('İletişim'),
            tileColor: Colors.white,
          ),
          ListTile(
            leading: Icon(Icons.exit_to_app_rounded),
            title: Text('Çıkış'),
            tileColor: Colors.white,
          ),
        ],
      ),
    );
  }
}

theme.dart

ThemeData light = ThemeData(
    brightness: Brightness.light,
    primarySwatch: Colors.blue,
    accentColor: Colors.blue,
    scaffoldBackgroundColor: Color(0xfff1f1f1));

ThemeData dark = ThemeData(
  brightness: Brightness.dark,
  primarySwatch: Colors.indigo,
  accentColor: Colors.green[700],
);

class ThemeNotifier extends ChangeNotifier {
  final String key = "theme";
  SharedPreferences _prefs;
  bool _darkTheme;

  bool get darkTheme => _darkTheme;

  ThemeNotifier() {
    _darkTheme = true;
    _loadFromPrefs();
  }

  toggleTheme() {
    _darkTheme = !_darkTheme;
    _saveToPrefs();
    notifyListeners();
  }

pubspec.yaml

name: mto
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  firebase_database: ^4.3.0
  page_transition: ^1.1.7+2
  simple_animations: ^2.2.3
  curved_navigation_bar: ^0.3.4
  provider: ^4.3.2+2
  shared_preferences: ^0.5.12+4

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter


# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/images/
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

应用程序如下所示

enter image description here

【问题讨论】:

    标签: android flutter dart switch-statement android-dark-theme


    【解决方案1】:

    我复制了您上面的代码,但有一些例外,我不得不注释掉一些行代码。代码按预期工作。我可以通过点击开关将主题从黑暗切换到明亮。请看录屏。还要检查我在下面复制的代码。

    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:shared_preferences/shared_preferences.dart';
    import 'package:curved_navigation_bar/curved_navigation_bar.dart';
    
    void main() => runApp(
          ChangeNotifierProvider<ThemeNotifier>(
            create: (_) => ThemeNotifier(),
            child: MyApp(),
          ),
        );
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final ThemeNotifier notifier = Provider.of<ThemeNotifier>(context);
        return MaterialApp(
          title: 'Flutter Theme Provider',
          theme: notifier.darkTheme ? dark : light,
          home: Anasayfa(),
        );
      }
    }
    
    class Anasayfa extends StatefulWidget {
      @override
      _AnasayfaState createState() => _AnasayfaState();
    }
    
    class _AnasayfaState extends State<Anasayfa> {
      int currentPage = 0;
    
      nested() {
        return NestedScrollView(
            headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
              return [
                SliverAppBar(
                  toolbarHeight: 40,
                  expandedHeight: 92.0,
                  floating: false,
                  pinned: true,
                  flexibleSpace: FlexibleSpaceBar(
                      // background: Image.asset(
                      //   "assets/images/besmele.jpg",
                      //   fit: BoxFit.cover,
                      // ),
                      ),
                  actions: [
                    IconButton(
                      icon: Icon(Icons.account_circle),
                      color: Colors.white,
                      onPressed: () {},
                    ),
                  ],
                )
              ];
            },
            body: Container());
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: nested(),
          drawer: Drawer(
            child: DrawerDosyasi(),
          ),
          bottomNavigationBar: CurvedNavigationBar(
            color: Colors.blue,
            backgroundColor: Colors.white,
            buttonBackgroundColor: Colors.blue,
            height: 50,
            items: <Widget>[
              Icon(
                Icons.campaign,
                size: 20,
                color: Colors.white,
              ),
              Icon(
                Icons.supervisor_account,
                size: 20,
                color: Colors.white,
              ),
              Icon(
                Icons.home,
                size: 20,
                color: Colors.white,
              ),
              Icon(
                Icons.video_collection_rounded,
                size: 20,
                color: Colors.white,
              ),
              Icon(
                Icons.menu_book_rounded,
                size: 20,
                color: Colors.white,
              ),
            ],
            animationDuration: Duration(
              milliseconds: 300,
            ),
            index: 2,
            animationCurve: Curves.bounceInOut,
            onTap: (index) {
              debugPrint("Current index is $index");
            },
          ),
        );
      }
    }
    
    class DrawerDosyasi extends StatefulWidget {
      @override
      _DrawerDosyasiState createState() => _DrawerDosyasiState();
    }
    
    class _DrawerDosyasiState extends State<DrawerDosyasi> {
      @override
      Widget build(BuildContext context) {
        return Container(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                decoration: BoxDecoration(
                  color: Colors.blue,
                ),
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Consumer<ThemeNotifier>(
                        builder: (context, notifier, child) => Switch(
                          onChanged: (val) {
                            notifier.toggleTheme();
                          },
                          value: notifier.darkTheme,
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 3,
                      child: CircleAvatar(
                        radius: 60,
                        backgroundColor: Colors.white,
                      ),
                    ),
                    Expanded(flex: 1, child: SizedBox.expand()),
                  ],
                ),
              ),
              ListTile(
                leading: Icon(Icons.home),
                title: Text('Anasayfa'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.account_circle),
                title: Text('Profil'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.campaign),
                title: Text('Duyurular'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.account_box),
                title: Text('Hocalar'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.library_books),
                title: Text('Dergiler'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.video_collection_rounded),
                title: Text('Canlı Dersler'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.menu_book_rounded),
                title: Text('Kütüphane'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.supervisor_account),
                title: Text('Tartışmalar'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.create),
                title: Text('Yazı Gönder'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.message_rounded),
                title: Text('İletişim'),
                tileColor: Colors.white,
              ),
              ListTile(
                leading: Icon(Icons.exit_to_app_rounded),
                title: Text('Çıkış'),
                tileColor: Colors.white,
              ),
            ],
          ),
        );
      }
    }
    
    ThemeData light = ThemeData(
        brightness: Brightness.light,
        primarySwatch: Colors.blue,
        accentColor: Colors.blue,
        scaffoldBackgroundColor: Color(0xfff1f1f1));
    
    ThemeData dark = ThemeData(
      brightness: Brightness.dark,
      primarySwatch: Colors.indigo,
      accentColor: Colors.green[700],
    );
    
    class ThemeNotifier extends ChangeNotifier {
      final String key = "theme";
      SharedPreferences _prefs;
      bool _darkTheme;
    
      bool get darkTheme => _darkTheme;
    
      ThemeNotifier() {
        _darkTheme = true;
        //_loadFromPrefs();
      }
    
      toggleTheme() {
        _darkTheme = !_darkTheme;
        //_saveToPrefs();
        notifyListeners();
      }
    }
    

    【讨论】:

    • 感谢您的回答。我仔细研究了代码。 -首先,我注意到你使用了太多的“const”。为什么?我想学习。 -我试着一一复制像你这样的代码。但是得到了同样的错误。 -我用 ctrl + c 复制了你的代码并粘贴到我的。得到同样的错误。 -最后,我将其他页面的所有行代码注释掉,复制所有代码并粘贴到一个页面。但得到了同样的错误。
    • 您的代码没有问题。您是否正确添加了 provider: 在 pubspec.yaml 文件中。您使用的是什么版本的提供程序? const 构造函数帮助 Flutter 仅重建应该更新的小部件。由于 const 是编译时常量,它们通过让 Flutter 知道该对象在代码的整个运行时永远不会改变来提高应用程序的性能。我使用 dart lint dart-lang.github.io/linter/lints 标记 IDE 中我需要输入 const 的代码。
    • 我检查了我的 pubspec.yaml 文件。提供者的版本是“提供者:^4.3.2+2”所以最后一个版本。如果需要,我可以将 pubspec.yaml 文件添加到上面的正文中。感谢您解释 const。
    • 是的,请将您的 pubspec.yaml 添加到您的主要问题中。
    • 好的,我添加了 pubspec.yaml 文件
    猜你喜欢
    • 2015-12-23
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多