【问题标题】:Dart, Nested classes, how to access child class variablesDart,嵌套类,如何访问子类变量
【发布时间】:2019-08-10 02:30:48
【问题描述】:

我是 Dart/Flutter 的新手。所以请原谅我。我正在尝试创建一个下面提到的 TestData 对象类。 TestData 中的变量之一是 TestChildClass 的 Map。如何访问子变量并设置它们。并得到它们。

    class TestData{
  int id;
var childClass = new Map<TestChildClass, String>();
TestData.items({
    this.id,
  this.childClass

});
}

class TestChildClass{
  int childid;

}

List <TestData> data = [
  TestData.items(
    id: 1,

    //childClass: {TestChildClass.:1, 1} how do i set and get this 
  )
];

也是对此的跟进。

如何遍历 Map 并迭代字符串中的值。我想要一个简单的 childClass.getData 函数。它通过 childClass 并转换字符串中的所有 Key 值。

谢谢!

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    只需在TestChildClass 类之后添加() 即可在List 中定义Map

    class TestData{
      int id;
      var childClass = new Map<TestChildClass, dynamic>();
      TestData.items({
        this.id,
        this.childClass
    
      });
    }
    
    class TestChildClass{
      int childid;
    
    }
    
    List <TestData> data = [
      TestData.items(
        id: 1,
        childClass: {TestChildClass()..childid=5:"anything"},
      )
    ];
    

    【讨论】:

      【解决方案2】:

      你可以这样做(将构造函数添加到TestChildClass

      class TestData{
        int id;
        var childClass = new Map<TestChildClass, dynamic>();
        TestData.items({
          this.id,
        this.childClass
      
        });
      }
      
      class TestChildClass{
        TestChildClass(this.childid);
        int childid;
      
      }
      
      List <TestData> data = [
        TestData.items(
          id: 1,
      
          childClass: {TestChildClass(1): 1}
        )
      ];
      

      【讨论】:

        【解决方案3】:
        class APIConstant {
          static RequestKeys requestKeys = const RequestKeys();
          static ResponseKeys responseKeys = const ResponseKeys();
        
          static const String baseUrl = 'Your Project base url';
        }
        
        class RequestKeys {
          const RequestKeys();
          String get email => 'email';
          String get password => 'password';
        }
        
        class ResponseKeys {
          const ResponseKeys();
          String get data => 'data';
          String get status => 'status';
        }
        

        你可以这样使用:

        print(APIConstant.requestKeys.email);
        print(APIConstant.requestKeys.email);
        print(APIConstant.baseUrl);
        

        【讨论】:

          猜你喜欢
          • 2021-04-28
          • 2015-04-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-10
          • 2015-08-13
          • 2022-06-23
          • 1970-01-01
          相关资源
          最近更新 更多