【问题标题】:Where to add custom colors in ThemeData in FlutterFlutter 中 ThemeData 在哪里添加自定义颜色
【发布时间】:2020-03-16 20:20:37
【问题描述】:

我是初学者,最近才开始学习 Flutter。

在网上搜索了很长时间,终于找到了一个解释如何添加动态主题转换器的教程。

现在这很完美 - 但是我仍然不知道应该在哪里以及如何添加我的自定义颜色,例如

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

在主题数据中。

我将在下面发布我的代码,请帮助我。

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());
    }
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    如果你构造一个普通的 ThemeData 类,那么有很多属性可以赋值。例如,ThemeData(primaryColor: Colors.red),但如果你使用像ThemeData.light() 这样的命名构造函数,Flutter 会将所有默认值放入标准轻主题,ThemeData.dark() 也是如此。所以你可以做的是使用copyWith() 方法以某种方式覆盖默认值ThemeData.light().copyWith(primaryColor: Colors.white, accentColor: Colors.green,)

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2011-03-17
      • 1970-01-01
      • 2019-02-17
      相关资源
      最近更新 更多