【问题标题】:Change color with flutter variable使用 flutter 变量改变颜色
【发布时间】:2023-01-29 04:24:45
【问题描述】:

我的项目中使用的颜色有两种颜色需要更改。这些颜色将根据主题而变化,主题数据将从 API 中获取。现在的问题是我手动把theme给了test变量而不是api,但是我给int的值之后并没有改变。无论我在开始时给 int 什么,它都会保留。 常量飞镖:

import 'package:flutter/material.dart';

int koyuMor = 0xff410657;
int acikMor = 0xff5B336A;
int lacivert = 0xff0D1665;
int mavi = 0xff009DA4;
int koyuYesil = 0xff055511;
int acikYesil = 0xff8DA637;
int koyuTuruncu = 0xffC83232;
int acikTuruncu = 0xffDB7439;
var theme = 'ocean - theme';
int _color1 = 0;
int _color2 = 0;

void main() {
  if (theme == 'thinker-theme') {
    _color1 = koyuMor;
    _color2 = acikMor;
  }
  if (theme == 'ocean-theme') {
    _color1 = lacivert;
    _color2 = mavi;
  }
  if (theme == 'forest-theme') {
    _color1 = koyuYesil;
    _color2 = acikYesil;
  }
  if (theme == 'sand-theme') {
    _color1 = koyuTuruncu;
    _color2 = acikYesil;
  }
}

class Constant {
  /// [Colors]
  static Color color1 = Color(_color1);
  static final Color color2 = Color(_color2);
  static const Color koyuMor = Color(0x00410657);
  static const Color acikMor = Color(0xff5B336A);
  static const Color mavi = Color(0xff009DA4);
  static const Color lacivert = Color(0xff0D1665);
  static const Color koyuYesil = Color(0xff055511);
  static const Color acikYesil = Color(0xff8DA637);
  static const Color koyuTuruncu = Color(0xffC83232);
  static const Color acikTuruncu = Color(0xffDB7439);
}

我也尝试过 ThemeData,以后似乎无法更改它。

我在其他页面中使用的代码:

color: Constant.color2,

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您正在尝试根据从 API 检索到的主题更改项目的颜色。但是,问题是当您手动为主题变量赋值时颜色不会改变。

    问题是您提供的代码仅在程序启动时设置一次颜色,并且在主题变量更改时不会更新颜色。要在主题更改时更新颜色,您需要将设置颜色的代码移动到一个函数中,并在主题更改时调用该函数。此外,您需要确保主题变量已更新为您从 API 获得的值。

    您还可以考虑使用 ChangeNotifier 和 ChangeNotifierProvider 来管理主题状态并在主题更改时自动更新颜色。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2020-12-27
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2019-01-27
      • 2022-10-23
      相关资源
      最近更新 更多