简体   繁体   中英

how create a class in dart or flutter correctly

I would like to create a class with private properties with his constructors, getters and setters, and besides typical methods to manipulate the data.

Is the constructor definided correctly? (what is the diference between @required or required)

How could I write correctly this constructor?

Actividad({required _id, required _nombre});

My code is the following:

class Actividad{
  int _id;
  String _nombre;

  Actividad({required _id, required _nombre});

  int get id => _id;
  String get nombre => _nombre;

  set id(int nuevoId) {
    _id = nuevoId;
  }
  set nombre(String nuevoNombre) {
    _nombre = nuevoNombre;
  }

  Map<String, dynamic> toMap() {
    return {
      'id': _id,
      'nombre': _nombre
    };
  }

  @override
  String toString() {
    return 'Actividad{id: $_id, nombre: $_nombre}';
  }
}

See below:

class Actividad {
  int id;
  String nombre;

  Actividad({required this.id, required this.nombre});

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'nombre': nombre
    };
  }

  @override
  String toString() {
    return 'Actividad{id: $id, nombre: $nombre}';
  }
}

This is how I would write the class. Few points:

  • the way you written, I do not see the need of explicitly defining setters and getters, unless you want to put something in them
  • You may consider making fields id and more final - this will make your Actividad objects immutable
  • required is now reserved word and is strongly checked by compiler. @required is annotation from past that was only used by linter suggesting you to pass value if you don't

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM