Home > Mobile >  Flutter Nested Object (Basics)
Flutter Nested Object (Basics)

Time:10-26

Below is an attempted nested object.

class AppColors {
  static const light = {
    final backgroundSolid = const Color.fromRGBO(255, 255, 255, 1);
    final backgroundPrimary = const Color.fromRGBO(255, 255, 255, 0.84);
  },
  static const dark = {
      final backgroundSolid = const Color.fromRGBO(0, 0, 0, 1);
      final backgroundPrimary = const Color.fromRGBO(0, 0, 2550 0.84);
  }
}

The error is on the use of final on the first line item. What is the correct way of creating nested objects?

CodePudding user response:

Dart is a pretty flexible language, there is not really a correct way

You could certainly implement it using Maps, but you would lose the autocomplete and safety that a class has:

class AppColors {
//These are maps, note the `:` to separate key and values
  static const light = {
  'backgroundSolid' : const Color.fromRGBO(255, 255, 255, 1);
   'backgroundPrimary' : const Color.fromRGBO(255, 255, 255, 0.84);
};
static const dark = {
 'backgroundSolid' : const Color.fromRGBO(0, 0, 0, 1);
'backgroundPrimary' : const Color.fromRGBO(0, 0, 2550 0.84);
};
}

void main()
{
final  backgroundLight=AppColors.light['backgroundPrimary'];

}

However this is how I would code it. This way you have a class holding the attributes you need, if more are added, the dart analyzer will make you refactor the factory constructors to add/delete new fields. And the access to the properties feels quite clean too.

class AppColors {
  final Color backgroundSolid;
  final Color backgroundPrimary;

  AppColors({required this.backgroundSolid, required this.backgroundPrimary});

  factory AppColors.light()=>
      AppColors(backgroundSolid: const Color.fromRGBO(255, 255, 255, 1),
          backgroundPrimary: const Color.fromRGBO(255, 255, 255, 0.84));
  factory AppColors.dark()=>
      AppColors(backgroundSolid: const Color.fromRGBO(0, 0, 0, 1),
          backgroundPrimary: const Color.fromRGBO(0, 0, 0, 0.84));

}

void main()
{
final  backgroundLight=AppColors.light().backgroundPrimary;

}

  • Related