简体   繁体   English

如何更改 flutter 中的主题数据?

[英]how to change theme data in flutter?

class _NavigationBarState extends State<NavigationBar> {
  int _currentIndex = 0;
  final List<Widget> tabs = [
    CustomerAccountPage(),
    HomePage(),
    AppInforamtionPage(),
    CategoriesPage(),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light().copyWith(
        primaryColor: Colors.amber,
        accentColor: Colors.black
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          showUnselectedLabels: true,
            unselectedItemColor: Theme.of(context).primaryColor,
            selectedItemColor: Theme.of(context).accentColor,
            currentIndex: _currentIndex,
            items: [
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                title: Text("account"),
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.play_for_work),
                title: Text("shop"),
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.all_out),
                title: Text("more info "),
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.all_out),
                title: Text(" categories"),
              ),
            ],
            onTap: (index) {
              setState(() {
                _currentIndex = index;
              });
            }),
       
          ),
          centerTitle: true,
          backgroundColor: Colors.white,
        ),
        body: tabs[_currentIndex],
        floatingActionButton: FloatingActionButton(onPressed: null, backgroundColor: Theme.of(context).primaryColor,),
      ),
    );
  }
}

I'm using flutter, and trying to set the theme data, but it doesn't work.我正在使用 flutter,并尝试设置主题数据,但它不起作用。 I tried to change the theme in this way, but I can't see the result in my app, I don't know what is the problem, can anyone help me!我尝试用这种方式更改主题,但在我的应用程序中看不到结果,我不知道是什么问题,任何人都可以帮助我!
stackoverflow want from me to explain more, but I haven't anything else to explain, thanks in advance! stackoverflow希望我解释更多,但我没有其他要解释的,提前谢谢!

The context used in Theme.of(context).primaryColor is not the right context. Theme.of(context).primaryColor中使用的上下文不是正确的上下文。 You need to put the MaterialApp in another widget wrapping the current widget, eg,您需要将MaterialApp放在包装当前小部件的另一个小部件中,例如,

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.light()
          .copyWith(primaryColor: Colors.amber, accentColor: Colors.black),
      home: NavigationBar(),
    );
  }
}

And the build method of the _NavigationBarState :以及_NavigationBarStatebuild方法:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
          showUnselectedLabels: true,
          unselectedItemColor: Theme.of(context).primaryColor,
          selectedItemColor: Theme.of(context).accentColor,
...

After trying very hard to understand Material Design, I found the following solution which is easy and clean.在非常努力地理解 Material Design 之后,我发现了以下简单干净的解决方案。 Here is my complete code.这是我的完整代码。

color_scheme.dart color_scheme.dart

import 'package:flutter/material.dart';

const lightColorScheme = ColorScheme(
  brightness: Brightness.light,
  primary: Color(0xFF687DAF),
  onPrimary: Color(0xFFFFFFFF),
  secondary: Color(0xFFf37b67),
  onSecondary: Color(0xFFFFFFFF),
  error: Color(0xFFBA1A1A),
  onError: Color(0xFFFFFFFF),
  background: Color(0xFFFEFFFF),
  onBackground: Color(0xFF3b3b3b),
  surface: Color(0xFFFEFFFF),
  onSurface: Color(0xFF3b3b3b),
);

const darkColorScheme = ColorScheme(
  brightness: Brightness.dark,
  primary: Color(0xFFADC6FF),
  onPrimary: Color(0xFF002E69),
  secondary: Color(0xFFBBC6E4),
  onSecondary: Color(0xFF253048),
  error: Color(0xFFFFB4AB),
  onError: Color(0xFF690005),
  background: Color(0xFF1B1B1F),
  onBackground: Color(0xFFE3E2E6),
  surface: Color(0xFF1B1B1F),
  onSurface: Color(0xFFE3E2E6),
);

theme.dart主题.dart

import 'package:first_project/shared/color_schemes.dart';

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

final ThemeData lightThemeDataCustom = _buildLightTheme();

ThemeData _buildLightTheme() {
  final ThemeData base = ThemeData.light();
  return base.copyWith(
    colorScheme: lightColorScheme,
    primaryColor: lightColorScheme.primary,
    scaffoldBackgroundColor: lightColorScheme.background,
    textTheme: GoogleFonts.montserratTextTheme(ThemeData.light().textTheme),
  );
}

final ThemeData darkThemeDataCustom = _buildDarkTheme();

ThemeData _buildDarkTheme() {
  final ThemeData base = ThemeData.dark();
  return base.copyWith(
    colorScheme: darkColorScheme,
    primaryColor: darkColorScheme.primary,
    scaffoldBackgroundColor: darkColorScheme.background,
    textTheme: GoogleFonts.montserratTextTheme(ThemeData.dark().textTheme),
  );
}

main.dart main.dart

import 'package:first_project/shared/theme_two.dart';
import 'package:flutter/services.dart';

import '../screens/bottom_bar.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark));

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: lightThemeDataCustom,
      darkTheme: darkThemeDataCustom,
      home: const BottomBar(),
    );
  }
}


If you follow this approach, then you don't need to define colors in each and every widget.如果您遵循这种方法,那么您不需要在每个小部件中定义 colors。 Just change the color scheme, flutter will automatically change colors according to Light theme and Dark theme.只需更改配色方案,flutter 会根据 Light 主题和 Dark 主题自动更改 colors。

I do not add textTheme customization code but you can do it in theme.dart file.我不添加 textTheme 自定义代码,但您可以在 theme.dart 文件中添加。

Hope this will help someone.希望这会对某人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM