flutter 使用setter设置字段值,字段名称和值作为参数

7tofc5zh  于 2022-12-05  发布在  Flutter
关注(0)|答案(1)|浏览(227)

我在尝试构建一个应用程序时遇到了一个问题。问题是试图用一个通用的setField函数设置SomeClass中的字段。我的实现是这样的,但是遇到了this[fieldName]的问题;

已编辑

class TestClass {
  String name; // <- to set this the memberName = 'name';
  int age; // <- to set this the memberName = 'age';
  // and both will use the same setField as setter.

  TestClass({required name, required age});
  // the prev code is correct and no problem with it. 

  /** the use will be like this to set the value of name **/
  /** test.setField(memberName : 'name', valueOfThatMemberName: 'test name'); // notice here **/

  /** the use will be like this to set the value of age **/
  /** test.setField(memberName : 'age', valueOfThatMemberName: 15); // notice here **/

  void setField({required String memberName, required var valueOfThatMemberName}) {
    // some extra validation and logic,..
    this[memberName] = valueOfThatMemberName; // this gives this error:
  /** Error: The operator '[]=' isn't defined for the class 'TestClass'. **/
  }
  
  // this will return the valueOfThePassedMemberName;
  getField({required String memberName}) {
    return this[memberName]; // <= this gives this error
  /** Error: The getter 'memberName' isn't defined for the class 'TestClass'. **/
    
  }
}

void main() {
  TestClass test = TestClass(name: 'alaa', age: 14);

  /** here is the way to use it. **/
  test.setField(memberName: 'name', valueOfThePassedMemberName: 'test name'); // notice here
  test.setField(memberName: 'age', valueOfThePassedMemberName: 16); // notice here
  print(test.getField(memberName: 'name')); // <- this should print the name of test object.
}

只通过setField方法设置值。

添加可运行JS代码

// i need to do the exact same thing here with the dart.
export class Entity {
  constructor(data: {}) {
    Object.keys(data).forEach(key => {
      this.set(key, data[key], true);
    });
  }

  get(field: string) {
    return this["_" + field];
  }

  set(field: string, value: any, initial = false) {
    this["_" + field] = value;
  }
}
zf9nrax1

zf9nrax11#

class TestClass {
  late String fieldName;
  late dynamic value;

  TestClass({required fieldName, required value});

  void setField({required String fieldName, required var value}) {
    // some extra validation and logic,..
    this.fieldName = fieldName;
    this.value = value;
  }

  getField() {
    return fieldName;
  }
  
  getValue() {
    return value;
  }
}

void main() {
  TestClass test = TestClass(fieldName: 'name', value: 'Alaa');
  
  
  test.setField(fieldName: 'name', value: 'Alaa');
  print('${test.getField()}: ${test.getValue()} ');
  
  test.setField(fieldName: 'age', value: 14);
  print('${test.getField()}: ${test.getValue()} ');
  
}

相关问题