【问题标题】:Flutter - dynamically change container colorFlutter - 动态改变容器颜色
【发布时间】:2021-05-15 10:18:20
【问题描述】:

我的颤振应用程序有问题。 在我的抽屉里,我创建了一个切换按钮来在浅色和深色风格之间切换。

现在这在大多数情况下都有效,但问题是我似乎无法动态更改抽屉容器颜色的颜色。

我能得到一些帮助吗,这让我发疯了?

此代码不起作用 - style: Theme.of(context).CustomColors().fusaBlue,

- theme_switch_widget.dart -
    import 'package:flutter/material.dart';
    
    import 'theme_switch_state.dart';
    
    class ThemeSwitch extends StatefulWidget {
      
      @override
      ThemeSwitchState createState() => new ThemeSwitchState();
    }

    - theme_switch_state.dart -
    import 'package:flutter/material.dart';
    
    import '../../themes/global/themes.dart';
    import 'themes_custom.dart';
    
    class ThemeSwitchState extends State {
      bool switchControl = false;
      //var textHolder = 'Theme is Light';
    
      @override
      Widget build(BuildContext context) {
        return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
          Transform.scale(
              scale: 1.5,
              child: Switch(
                onChanged: toggleSwitch,
                value: switchControl,
                activeColor: CustomColors().skyBlue,
                activeTrackColor: CustomColors().goreBlue,
                inactiveThumbColor: CustomColors().loreGrey,
                inactiveTrackColor: CustomColors().noroGrey,
              )),
          /*Text(
            '$textHolder',
            style: TextStyle(fontSize: 24),
          )*/
        ]);
      }
    
      void _changeTheme(BuildContext buildContext, MyThemeKeys key) {
        CustomTheme.instanceOf(buildContext).changeTheme(key);
      }
    
      void toggleSwitch(bool value) {
        if (switchControl == false) {
          setState(() {
            switchControl = true;
            //textHolder = 'Theme is Dark';
          });
          print('Theme is Dark');
    
          // Put your code here which you want to execute on Switch ON event.
          _changeTheme(context, MyThemeKeys.DARK);
    
        } else {
          setState(() {
            switchControl = false;
            //textHolder = 'Theme is Light';
          });
          print('Theme is Light');
    
          // Put your code here which you want to execute on Switch OFF event.
          _changeTheme(context, MyThemeKeys.LIGHT);
        }
      }
    }

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

class _ThemesCustom extends InheritedWidget {
  final CustomThemeState data;

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

  @override
  bool updateShouldNotify(_ThemesCustom 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) {
    _ThemesCustom inherited =
        (context.dependOnInheritedWidgetOfExactType<_ThemesCustom>());
    return inherited.data.theme;
  }

  static CustomThemeState instanceOf(BuildContext context) {
    _ThemesCustom inherited =
        (context.dependOnInheritedWidgetOfExactType<_ThemesCustom>());
    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 _ThemesCustom(
      data: this,
      child: widget.child,
    );
  }
}

- themes.dart -
import 'package:flutter/material.dart';

enum MyThemeKeys {
  LIGHT,
  DARK,
}

class CustomColors {
  final novaWhite = Color(0xffecf0f1);
  final loreGrey = Color(0xff6c7a84);
  final noroGrey = Color(0xff424b51);
  final skyBlue = Color(0xff1da1f2);
  final fusaBlue = Color(0xff053959);
  final goreBlue = Color(0xff032234);
  final limeGreen = Color(0xff3bd37b);
  final leafGreen = Color(0xff2ecc71);
  final sageGreen = Color(0xff208c4d);
}

class MyThemes {
  static TextTheme baseTextTheme(TextTheme base) {
    return base.copyWith(
      display4: base.display4.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.w100,
        fontSize: 112.0,
      ),
      display3: base.display3.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 56.0,
      ),
      display2: base.display2.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 45.0,
      ),
      display1: base.display1.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 34.0,
      ),
      headline: base.headline.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 24.0,
      ),
      title: base.title.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.w500,
        fontSize: 20.0,
      ),
      subhead: base.subhead.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 16.0,
      ),
      body2: base.body2.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.w500,
        fontSize: 14.0,
      ),
      body1: base.body1.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 14.0,
      ),
      caption: base.caption.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 12.0,
      ),
      button: base.button.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.w500,
        fontSize: 14.0,
      ),
      subtitle: base.subtitle.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.w500,
        fontSize: 14.0,
      ),
      overline: base.overline.copyWith(
        fontFamily: 'Iceland',
        fontWeight: FontWeight.normal,
        fontSize: 10.0,
      ),
    );
  }

  static final ThemeData lightTheme = ThemeData(
    brightness: Brightness.light,
    primaryColor: CustomColors().limeGreen,
    indicatorColor: CustomColors().loreGrey,
    accentColor: CustomColors().limeGreen,
    scaffoldBackgroundColor: CustomColors().novaWhite,

    iconTheme: IconThemeData(
      size: 30.0,
      color: CustomColors().noroGrey,
    ),
    dividerTheme: DividerThemeData(
      thickness: 0.5,
      indent: 16,
      endIndent: 16,
      color: CustomColors().limeGreen,
    ),
    buttonColor: CustomColors().novaWhite,
    backgroundColor: CustomColors().novaWhite,
  );

  static final ThemeData darkTheme = ThemeData(
    brightness: Brightness.dark,
    primaryColor: CustomColors().skyBlue,
    indicatorColor: CustomColors().loreGrey,
    accentColor: CustomColors().skyBlue,
    scaffoldBackgroundColor: CustomColors().novaWhite,
    iconTheme: IconThemeData(
      size: 30.0,
      color: CustomColors().noroGrey,
    ),
    dividerTheme: DividerThemeData(
      thickness: 0.5,
      indent: 16,
      endIndent: 16,
      color: CustomColors().skyBlue,
    ),
    buttonColor: CustomColors().novaWhite,
    backgroundColor: CustomColors().novaWhite,

  );

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

【问题讨论】:

  • 仅共享代码以切换您如何更改主题,以便我们为您提供帮助。与此同时,利用全班同学来挑选颜色并不是最好的方法。您应该在自定义颜色类中创建一个静态常量,并只选择常量来选择颜色。

标签: flutter dart colors containers


【解决方案1】:

无法评论,所以我写它作为答案。

  1. 确保您有 StatefulWidget,并在更改主题时使用 setState()。
  2. 您可以使用静态变量来检查它是亮模式还是暗模式,并相应地获取颜色。 (颜色:isDarkMode ? Colors.black : 颜色:白色)
  3. 如果您不想使用它,请分享切换按钮的 onTap 功能代码以及 CustomColors() 源代码。

【讨论】:

  • 在这里分享太多了——调解人会抱怨的。你还有什么可以分享的吗?
  • 我相信您可以编辑您的帖子并将其添加到那里。它不应该有任何限制。只需将其添加为源代码
  • 我已经添加了我的代码 - 请检查一下。这一切都在那里。请帮助我了解如何动态更新容器的颜色
  • 你的主要功能是什么样的?在使用 ThemeSwitch 小部件之前,您是否曾经调用(使用)CustomTheme 类?浅色和深色主题的某些颜色是相同的,也许您应该尝试为每个主题设置完全不同的颜色,然后再试一次。
  • 另外,要使用主题中的颜色,您应该使用 Theme.of(context)。例如:对于浅色 - 您有 - 重音颜色:CustomColors().limeGreen,对于深色 - 您有 - 重音颜色:CustomColors().skyBlue,要在小部件中使用此颜色,您应该使用 Theme.of(context).accentColor
【解决方案2】:

要更改容器的颜色,请按照以下简单步骤操作:

  1. 创建颜色变量c
Color c = const Color(0xFF42A5F5);

Color(...) 中的代码决定了颜色。颜色代码见this link

如果您喜欢深色,请在 if-else 条件下使用此选项,您选择的容器颜色将存储在 c 中,而对于浅色主题,将在 c 中保存不同的颜色。

  1. Container color 属性中调用如下:
color: c,

【讨论】:

    猜你喜欢
    • 2019-01-27
    • 2018-12-31
    • 2020-02-02
    • 1970-01-01
    • 2011-10-19
    • 2012-10-17
    • 2023-03-21
    • 2012-07-01
    • 1970-01-01
    相关资源
    最近更新 更多