首页 > 解决方案 > Where to add custom colors in ThemeData in Flutter

问题描述

I'm a beginner and only recently started learning Flutter.

After searching the web for a long time I finally managed to find a tutorial that explains how to add a dynamic theme changer.

Now this works perfectly - however I still don't get where & how I'm supposed to add my custom colors like

primaryColor: Colors.white, accentColor: Colors.green,

in ThemeData.

I will post my code below, please help me.

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return ChangeNotifierProvider<ThemeChanger>(
      create: (_) => ThemeChanger(ThemeData.light()),
      child: MaterialAppWithTheme(),
    );
  }
}

class MaterialAppWithTheme extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<ThemeChanger>(context);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: theme.getTheme(),
      home: MdLayout(),
    );
  }
}

theme.dart
class ThemeChanger with ChangeNotifier{
  ThemeData _themeData;

  ThemeChanger(this._themeData);

  getTheme() => _themeData;

  setTheme(ThemeData theme) {
    _themeData = theme;

    notifyListeners();
  }
}

theme_switch_state.dart
class ThemeSwitchState extends State {
  bool switchControl = false;

  @override
  Widget build(BuildContext context) {
    return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
      Transform.scale(
          scale: 1.5,
          child: Switch(
            onChanged: toggleSwitch,
            value: switchControl,
            activeColor: Colors.blue,
            activeTrackColor: Colors.grey,
            inactiveThumbColor: Colors.green,
            inactiveTrackColor: Colors.white,
          )),
    ]);
  }

  void toggleSwitch(bool value) {
    ThemeChanger _themeChanger = Provider.of<ThemeChanger>(context, listen: false);

    if (switchControl == false) {
      setState(() {
        switchControl = true;
      });
      print('Theme is Dark');

      // Put your code here which you want to execute on Switch ON event.
      _themeChanger.setTheme(ThemeData.dark());

    } else {
      setState(() {
        switchControl = false;
      });
      print('Theme is Light');

      // Put your code here which you want to execute on Switch OFF event.
      _themeChanger.setTheme(ThemeData.light());
    }
  }
}

标签: flutterdart

解决方案


If you construct normal ThemeData class, there are so many properties you can put value into. For instance, ThemeData(primaryColor: Colors.red), but if you use the named constructor like ThemeData.light(), Flutter put all the default values for a standard light theme, the same goes with ThemeData.dark(). So what you can do is to use copyWith() method to some sort overwritten the default values, ThemeData.light().copyWith(primaryColor: Colors.white, accentColor: Colors.green,).


推荐阅读