when trying to understand the functionality of copyWith() method in ThemeData class in Dart I created the function but when I use it it doesn't change the first value that I have passed before at the opposite of my expectation and I don't understand what I've missed in my code which causes this problem
My function:
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);
}
}
Input:
import 'Copywith.dart';
void main() {
var theme = ThemeData();
theme.copyWith(accentColor: Color.RED);
print(theme.accentColor);
}
Output:
Color.BLACK
CodePudding user response:
This is exactly what copyWith
is supposed to do - It does not change the instance upon which it is called, but rather creates a new instance which shares identical field values to the original, other than those values which are specified as arguments to copyWith
.
To demonstrate using a tweaked version of your example:
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
}