使用 copyWith()
的主要好处是,您不会改变原始对象,而是返回一个与原始对象具有相同属性但具有指定值的新对象。这允许您创建更易于测试和维护的应用程序,因为对象本身不具有可变状态。
您可以通过获取要更改的值并返回具有新值的新对象来创建自己的 copyWith
函数。
下面是一个包含 Product
类的示例:
class Product { final String id; final String name; final Color color; Product({this.id, this.color, this.name}); Product copyWith({String id, String name, Color color}) => Product( id: id ?? this.id, name: name ?? this.name, color: color ?? this.color, ); }
class _HomePageState extends State<HomePage> { List<Product> products = []; @override void initState() { super.initState(); Product sixSeaterDiningTableBrown = Product( id: "0", name: "6 Seater Dining Table", color: Colors.brown, ); Product sixSeaterDiningTableBlack = sixSeaterDiningTableBrown.copyWith(color: Colors.black, id: "1"); products.add(sixSeaterDiningTableBrown); products.add(sixSeaterDiningTableBlack); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Hello, copyWith!"), ), body: ListView( children: products .map((Product product) => ListTile( trailing: Container( width: 14, height: 14, color: product.color, ), title: Text(product.name), subtitle: Text(product.id), ), ) .toList(), ), ); } }