Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart, Nested classes, how to access child class variables

Tags:

flutter

dart

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!

like image 316
user1788504 Avatar asked Dec 06 '25 14:12

user1788504


2 Answers

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);
like image 131
Bhargav Sejpal Avatar answered Dec 08 '25 10:12

Bhargav Sejpal


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;

class _NestedClass { ... }

If you want your class to be public, and non-instantiable

part of main_class;

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

And In your main_class.dart, Instantiate with

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

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

like image 22
Jerin Avatar answered Dec 08 '25 10:12

Jerin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!