动态设置类的属性

问题描述 投票:0回答:2

我想通过传递变量字符串名称来设置类的属性。我怎样才能做到这一点?

与@Chad Lamb提供的get方法类似

class Person {
  String name;
  int age;

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

  Map<String, dynamic> _toMap() {
    return {
      'name': name,
      'age': age,
    };
  }

  dynamic get(String propertyName) {
    var _mapRep = _toMap();
    if (_mapRep.containsKey(propertyName)) {
      return _mapRep[propertyName];
    }
    throw ArgumentError('propery not found');
  }
}

main() {
  Person person = Person(age: 10, name: 'Bob');

  print(person.name); // 'Bob'

  print(person.get('name')); // 'Bob'
  print(person.get('age')); // 10

  // wrong property name
  print(person.get('wrong')); // throws error
}

我尝试了很多方法,但还没有成功。

flutter dart class parameter-passing
2个回答
0
投票

您可以设置一个操作员来完成此操作。

class Point {
  int x;
  int y;
  String name;
  Point({required this.x, required this.y, required this.name});

  @override
  toString() {
    return {"name": name, "x": "$x", "y": "$y"}.toString();
  }

  void operator []=(Object key, Object value) {
    switch (key) {
      case "x":
        x = value as int;
        break;
      case "y":
        y = value as int;
        break;
      case "name":
        name = value as String;
        break;
      default:
    }
  }
}

void main() {
  var point = Point(x: 1, y: 1, name: "A");
  print(point.toString());

  point["x"] = 2;
  point["y"] = 3;

  print(point.toString());
}

-1
投票

试试这个代码:

  try {
    print(person.get("wrong"));
  } on Error catch (e) {
    print(e);
  }

输出:

Invalid argument(s): propery not found
© www.soinside.com 2019 - 2024. All rights reserved.