当尝试了解 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/