'Dart, Nested classes, how to access child class variables

I am new to Dart/Flutter. So forgive me. I am trying to create a Object class mentioned as TestData below. And one of the variables in TestData is a Map of TestChildClass. How can I access the child variables and set them. and get them.

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

Also a follow up to this.

How do I go through the Map and iterate the values in a string. I want to have a simple childClass.getData function. that goes through the childClass and converts all Key values in a string.

Thank you!



Solution 1:[1]

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';
}

And you can use this like:

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

Solution 2:[2]

Just add () after TestChildClass class for defind Map in List.

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

Solution 3:[3]

You can do this way (add constructor to 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}
  )
];

Solution 4:[4]

The best way is using Bargav Sejpal's answer, but this might come in handy:

Create a main class as main_class.dart

library main_class;
part 'nested_class.dart';

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

and create your nested class as nested_class.dart

part of 'main_class.dart';

class _NestedClass { ... }

This way your nested class will be inaccessible directly. It can only be accessed via MainClass().nestedClass

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Saman
Solution 3 Andrey Turkovsky
Solution 4 DarkTrick