Deep copy in Dart for Flutter BLOC models

  • flutter
Reading time: < 1 minute

This one is especially useful when working with BLOC architecture, to update same state with new object. To handle this situation we can use same way as flutter library does itself. As example when applying style for text we can call copyWith(..) method that will return same style but changed the way we like. This is how it looks:

class Child {
  final int age;
  final String name;

  Child({this.age, this.name});

  Child copyWith({int age, String name}) {
    return Child(age: age ?? this.age, name: name ?? this.name);
  }
}

Next time we’ll have to create modified ‘child’ object this is how it looks:

var younger = Child(name:"Adam", age:9);
var older = younger.copyWith(nage:12);

Leave a Reply

Your email address will not be published. Required fields are marked *