class Course {
final int id;
final String name;
final String content;
final int hours;
const Course({
this.id = 0;
this.name = '';
this.content = '';
this.hours = 0;
});
factory Course.fromMap<String, dynamic> data) {
return Course(
id: data['id'] as int ?? 0,
name: data['name'] as String ?? '',
content: data['content'] as String ?? '',
hours: data['hours'] as int ?? 0,
);
}
}
...
final course = Course.fromMap(data);
2条答案
按热度按时间z2acfund1#
这是我们在Dart/Flutter中执行此操作的正常方式:
我们通常不对数据类使用下划线(私有)变量,因为Dart会自动提供getter来通过点标记法访问字段。
wqlqzqxt2#
不可为空的字段应该在对象创建期间初始化,甚至在构造函数体执行之前。