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

lyfkaqu1  于 2023-09-28  发布在  其他
关注(0)|答案(4)|浏览(150)

我是Dart/Flutter的新手。所以原谅我我试图创建一个Object类,下面提到TestData。TestData中的一个变量是TestChildClass的Map。如何访问子变量并设置它们。并得到他们。

  1. class TestData{
  2. int id;
  3. var childClass = new Map<TestChildClass, String>();
  4. TestData.items({
  5. this.id,
  6. this.childClass
  7. });
  8. }
  9. class TestChildClass{
  10. int childid;
  11. }
  12. List <TestData> data = [
  13. TestData.items(
  14. id: 1,
  15. //childClass: {TestChildClass.:1, 1} how do i set and get this
  16. )
  17. ];

这也是一个后续。
我如何遍历Map并将值转换为字符串。我想有一个简单的childClass.getData函数。它遍历childClass并转换字符串中的所有Key值。
谢谢你,谢谢!

bq9c1y66

bq9c1y661#

  1. class APIConstant {
  2. static RequestKeys requestKeys = const RequestKeys();
  3. static ResponseKeys responseKeys = const ResponseKeys();
  4. static const String baseUrl = 'Your Project base url';
  5. }
  6. class RequestKeys {
  7. const RequestKeys();
  8. String get email => 'email';
  9. String get password => 'password';
  10. }
  11. class ResponseKeys {
  12. const ResponseKeys();
  13. String get data => 'data';
  14. String get status => 'status';
  15. }

你可以这样使用:

  1. print(APIConstant.requestKeys.email);
  2. print(APIConstant.requestKeys.email);
  3. print(APIConstant.baseUrl);
展开查看全部
nwwlzxa7

nwwlzxa72#

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

  1. library main_class;
  2. part 'nested_class.dart';
  3. class MainClass {
  4. _NestedClass nestedClass = _NestedClass();
  5. // ...
  6. }

并将嵌套类创建为nested_class.dart

  1. part of main_class;
  2. class _NestedClass { ... }

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

  1. part of main_class;
  2. class NestedClass {
  3. NestedClass._(); // private constructor
  4. // ...
  5. }

在你的main_class.dart中,示例化

  1. class MainClass {
  2. final NestedClass nestedClass = NestedClass._();
  3. // ...
  4. }

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

展开查看全部
nhaq1z21

nhaq1z213#

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

  1. class TestData{
  2. int id;
  3. var childClass = new Map<TestChildClass, dynamic>();
  4. TestData.items({
  5. this.id,
  6. this.childClass
  7. });
  8. }
  9. class TestChildClass{
  10. int childid;
  11. }
  12. List <TestData> data = [
  13. TestData.items(
  14. id: 1,
  15. childClass: {TestChildClass()..childid=5:"anything"},
  16. )
  17. ];
展开查看全部
polhcujo

polhcujo4#

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

  1. class TestData{
  2. int id;
  3. var childClass = new Map<TestChildClass, dynamic>();
  4. TestData.items({
  5. this.id,
  6. this.childClass
  7. });
  8. }
  9. class TestChildClass{
  10. TestChildClass(this.childid);
  11. int childid;
  12. }
  13. List <TestData> data = [
  14. TestData.items(
  15. id: 1,
  16. childClass: {TestChildClass(1): 1}
  17. )
  18. ];
展开查看全部

相关问题