Flutter中如何获取自定义Student类对象的属性键名
获取Dart Student类的属性键名
你的Student类代码如下:
class Student{ int id; String name; Student({this.id,this.name}); }
以下是几种输出该类属性键名id和name的实现方式:
方式1:手动定义属性名列表
直接创建包含目标属性名的列表并输出,适合结构固定的简单类:
void main() { final studentPropertyKeys = ['id', 'name']; print(studentPropertyKeys); // 输出: [id, name] }
方式2:利用类的toJson方法获取键名
在类中实现toJson转换方法,通过转换后的Map提取键名:
class Student{ int id; String name; Student({this.id,this.name}); // 添加toJson方法 Map<String, dynamic> toJson() => { 'id': id, 'name': name, }; } void main() { final student = Student(); print(student.toJson().keys); // 输出: (id, name) }
方式3:使用dart:mirrors反射(非生产环境)
通过Dart反射动态获取类的实例属性名,注意Flutter生产环境禁用反射,仅适合开发调试场景:
import 'dart:mirrors'; void main() { final classMirror = reflectClass(Student); final propertyKeys = classMirror.declarations.values .where((decl) => decl is VariableMirror && !decl.isStatic) .map((decl) => MirrorSystem.getName(decl.simpleName)) .toList(); print(propertyKeys); // 输出: [id, name] }
内容的提问来源于stack exchange,提问作者dinesh balan
相关产品推荐
相关产品推荐

