Dart,嵌套类,如何访问子类变量

lyfkaqu1  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(100)

我是Dart/Flutter的新手。所以原谅我我试图创建一个Object类,下面提到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值。
谢谢你,谢谢!

bq9c1y66

bq9c1y661#

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);
nwwlzxa7

nwwlzxa72#

最好的方法是使用Bargav Sejpal的答案,但这可能会派上用场:
创建一个主类main_class.dart

library main_class;
part 'nested_class.dart';

class MainClass {
   _NestedClass nestedClass = _NestedClass();
   // ...
}

并将嵌套类创建为nested_class.dart

part of main_class;

class _NestedClass { ... }

如果你希望你的类是公共的,并且是不可示例化的

part of main_class;

class NestedClass { 
    NestedClass._(); // private constructor
    // ... 
}

在你的main_class.dart中,示例化

class MainClass {
    final NestedClass nestedClass = NestedClass._();
    // ...
}

这样你的嵌套类将无法直接访问。只能通过MainClass().nestedClass访问

nhaq1z21

nhaq1z213#

只需在List中定义MapTestChildClass类之后添加()

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"},
  )
];
polhcujo

polhcujo4#

你可以这样做(将构造函数添加到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}
  )
];

相关问题