dart - Dart 中 ThemeData 类的 copyWith() 方法

标签 dart

当尝试了解 Dart 中 ThemeData 类中 copyWith() 方法的功能时 我创建了该函数,但是当我使用它时,它并没有改变我之前传递的第一个值,这与我的期望相反,而且我不明白我在代码中错过了什么导致这个问题

我的功能:

enum Color {
  RED,
  BLUE,
  GREEN,
  YELLOW,
  BLACK,
}

enum Brightness {
  LIGHT,
  DARK,
}

class ThemeData {
  final Color accentColor;
  final Color backgroundColor;
  final Color buttonColor;
  final Brightness brightness;

  ThemeData(
      {this.accentColor = Color.BLACK,
      this.backgroundColor = Color.BLUE,
      this.brightness = Brightness.LIGHT,
      this.buttonColor = Color.RED});

  ThemeData copyWith(
      {Color? accentColor,
      Color? backgroundColor,
      Color? buttonColor,
      Brightness? brightness}) {
    return ThemeData(
        accentColor: accentColor ?? this.accentColor,
        backgroundColor: backgroundColor ?? this.backgroundColor,
        buttonColor: buttonColor ?? this.buttonColor,
        brightness: brightness ?? this.brightness);
  }
}

输入:

import 'Copywith.dart';

void main() {
  var theme = ThemeData();
  theme.copyWith(accentColor: Color.RED);
  print(theme.accentColor);
}

输出:

Color.BLACK

最佳答案

这正是 copyWith 应该做的 - 它不会更改调用它的实例,而是创建一个新实例,该实例与原始实例共享相同的字段值,除了那些指定为 copyWith 参数的值。

使用示例的调整版本进行演示:

import 'Copywith.dart';

void main() {
  var original = ThemeData();
  var changed = original.copyWith(accentColor: Color.RED);
  print(original.accentColor); // Output: Color.BLACK
  print(changed.accentColor); // Output: Color.RED
}

关于dart - Dart 中 ThemeData 类的 copyWith() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73859375/

相关文章:

firebase - 我无法从 firestore "Instance of ' Future<dynamic >'"获取数据

flutter - 在没有 BuildContext 的情况下预加载图像

dart - 检查字符串是否已存在于云 firestore 字段和 flutter 中的字段中

asynchronous - 我怎样才能等待一个变量

cross-domain - 没有服务器控制的跨域请求

dart - 如何处理可扩展表单上的 Controller TextField

flutter - Flutter/Firestore-错误:无法将类型 'List<String> Function(QuerySnapshot)'的值分配给类型 'List<dynamic>'的变量

android - 手势捕获的 Flutter 异常。在 showModalBottomSheet 中找不到 MediaQuery 小部件

dart - 为什么在AngularDart 0.10.0中不推荐使用Controller?

file - 如何使用Flutter同步(不等待)从Assets文件夹中读取文件