Flutter - Model Conventions

Table of Contents

Flutter Model Conventions

Utilize a lib/models folder for your classes Utilize initializer lists for simple setters instead of full constructors Utilize named constructors like .fromMap() to initialize objects from various inputs

Provide a toString method for simple outputs Provide serialization methods like toMap and toJSON to make conversions easier later

lib/models/record.dart

class Record {
  final String name;
  final int votes;
  final DocumentReference reference;

  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['votes'] != null),
        name = map['name'],
        votes = map['votes'];

  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$votes>";

  Map toMap() {
    return {
      'name': name,
      'votes': votes,
    };
  }
}