如何在按下按钮时更改应用程序的全局原色?

How to change the app global primary color in flutter on button press?

如何在按下按钮时在 flutter 中更改应用程序的全局原色以在具有 2 种不同原色的 2 个主题之间切换?

例如:

import 'package:flutter/material.dart';

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final darkColorForLightTheme = 0xff242f60;

  final lightColorForDarkTheme = 0xff03DAC5;

  @override
  Widget build(BuildContext context) {
    var isDark = true;
    var primaryColorHex = (isDark ? lightColorForDarkTheme : darkColorForLightTheme);
    var primaryColor = Color(primaryColorHex);
    return MaterialApp(
      title: 'Welcome to Flutter',
      theme: ThemeData.light().copyWith(
        primaryColor: primaryColor,
        brightness: Brightness.light,
        backgroundColor: const Color(0xFFE5E5E5),
        dividerColor: Colors.white54,
        colorScheme: ColorScheme.light(primary: primaryColor),
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Welcome to Flutter'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('Hello World'),
              MaterialButton(
                  color: primaryColor,
                  onPressed: () {
                    setState(() {
                      isDark = !isDark;
                    });
                  },
                  child: const Text('Change app primary color')),
            ],
          ),
        ),
      ),
    );
  }
}

这是我如何处理更改整个项目主题的方式的示例。

1.- 创建一个 主题 class。在这里您可以添加一个或多个主题。

import 'package:flutter/material.dart';

enum MyThemeKeys { LIGHT, DARK }

class MyThemes {

  static final ThemeData lightTheme = ThemeData(
    primaryColor: Colors.blue,
    appBarTheme: AppBarTheme(color: Color(0xff171d49),),
    textSelectionTheme: TextSelectionThemeData(
      selectionColor: Colors.grey,
      cursorColor: Color(0xff171d49),
      selectionHandleColor: Color(0xff005e91),
    ),
    backgroundColor: Colors.white,
    brightness: Brightness.light,
    highlightColor: Colors.white,
    floatingActionButtonTheme:
      FloatingActionButtonThemeData (backgroundColor: Colors.blue,focusColor: Colors.blueAccent , splashColor: Colors.lightBlue),
    colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.white),

  );

  static final ThemeData darkTheme = ThemeData(
    primaryColor: Colors.grey,
    brightness: Brightness.dark,
    highlightColor: Colors.white,
    backgroundColor: Colors.black54,
    textSelectionTheme: TextSelectionThemeData(selectionColor: Colors.grey),
  );

  static ThemeData getThemeFromKey(MyThemeKeys themeKey) {
    switch (themeKey) {
      case MyThemeKeys.LIGHT:
        return lightTheme;
      case MyThemeKeys.DARK:
        return darkTheme;
      default:
        return lightTheme;
    }
  }
}

2.- 创建一个 CustomTheme Class。您将可以使用此更改主题。

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:YourProjectName/themes.dart';

class _CustomTheme extends InheritedWidget {
  final CustomThemeState data;

  _CustomTheme({
    this.data,
    Key key,
    @required Widget child,
  }) : super(key: key, child: child);

  @override
  bool updateShouldNotify(_CustomTheme oldWidget) {
    return true;
  }
}

class CustomTheme extends StatefulWidget {
  final Widget child;
  final MyThemeKeys initialThemeKey;

  const CustomTheme({
    Key key,
    this.initialThemeKey,
    @required this.child,
  }) : super(key: key);

  @override
  CustomThemeState createState() => new CustomThemeState();

  static ThemeData of(BuildContext context) {
    _CustomTheme inherited =
     (context.dependOnInheritedWidgetOfExactType<_CustomTheme>());
    return inherited.data.theme;
  }

  static CustomThemeState instanceOf(BuildContext context) {
    _CustomTheme inherited =
     (context.dependOnInheritedWidgetOfExactType<_CustomTheme>());
    return inherited.data;
  }
}

class CustomThemeState extends State<CustomTheme> {
  ThemeData _theme;

  ThemeData get theme => _theme;

  @override
  void initState() {
    _theme = MyThemes.getThemeFromKey(widget.initialThemeKey);
    super.initState();
  }

  void changeTheme(MyThemeKeys themeKey) {
    setState(() {
      _theme = MyThemes.getThemeFromKey(themeKey);
    });
  }

  @override
  Widget build(BuildContext context) {
    return new _CustomTheme(
      data: this,
      child: widget.child,
    );
  }
}

3.- 最后将其与您的代码一起使用

import 'package:flutter/material.dart';
import 'package:YourProjectName/custom_theme.dart';
import 'package:YourProjectName/themes.dart';

void main() async {
 runApp( CustomTheme(
    initialThemeKey: MyThemeKeys.LIGHT,
    child: MyApp(),
  ));
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: CustomTheme.of(context),
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Welcome to Flutter'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('Hello World'),
              MaterialButton(
                  color: Theme.of(context).primaryColor, //your Theme color
                  onPressed: () {
                    setState(() {
                      CustomTheme.instanceOf(context).changeTheme(MyThemeKeys.DARK);
                    });
                  },
                  child: const Text("I'm dark now")),
              MaterialButton(
                  color: Theme.of(context).primaryColor,//your Theme color
                  onPressed: () {
                    setState(() {
                      CustomTheme.instanceOf(context).changeTheme(MyThemeKeys.LIGHT);
                    });
                  },
                  child: const Text("I'm light now")),
            ],
          ),
        ),
      ),
    );
  }
}

应该是这样的