I find it's difficult to do a shallow copy and modify some attributes at the same time like spread syntax in javascript.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
The following are some js example.
const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };
const clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }
const mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }
The releated topic is rest parameters.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
Dart does have spread operator. Only for lists, tho.
@mateusfccp Thanks for your tips. I think object spread is more useful. For example I just want to copy the theme data object or some other object, and modify some instance variables. Without this features, maybe I need to write an extra function to do it.
Hope dart could support object spread operator too.
You can use code-generators to help until Dart has a proper syntax for it.
One of them would be: https://github.com/rrousselGit/freezed
(made by me)
It has support for a pretty good "copyWith"
Yes, it would be useful.
Currently, a common pattern in Flutter (don't know if it is also for Dart) is to make a function copyWith, where you provide only the fields you want to be different, and the rest is copied from the source.
For example, it's used in Flutter's themes/styles.
https://api.flutter.dev/flutter/painting/TextStyle/copyWith.html
Dart does have spread operator. Only for lists, tho.
Spreads work with all collection types in Dart: lists, maps, and sets. This is a valid Dart program:
main() {
const parts = ['shoulders', 'knees'];
const lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
const obj1 = { 'foo': 'bar', 'x': 42 };
const obj2 = { 'foo2': 'baz', 'y': 13 };
const clonedObj = { ...obj1 };
// Object { foo: "bar", x: 42 }
const mergedObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }
}
All I did was take that JS, put it inside main(), quote the map keys, and rename the second foo so that it doesn't collide with the first. :)
@munificent Hi, if i have a identity key in both maps, then this behavior is error in dart, how can I achieve it in dart with a clean and simple way?

Update I need to change const to var to make above works.
main() {
const obj1 = {'foo': 'bar', 'x': 42};
const obj2 = {'foo': 'baz', 'y': 13};
var clonedObj = {...obj1, 'x': 43};
// var clonedObj = {...obj1}..['x'] = 43;
var mergedObj = {...obj1, ...obj2, 'x': 43};
// var mergedObj = {}..addAll(obj1)..addAll(obj2);
}
Most helpful comment
@munificent Hi, if i have a identity key in both maps, then this behavior is error in dart, how can I achieve it in dart with a clean and simple way?
Update I need to change const to var to make above works.