Nested classes in Dart


How to create nested structure like Theme.colors.primary ? I js/ts if i want to create an app theme like this it would be:

class Theme {
 public colors = {
  primary: '#ff0000'

And in Dart ? Something like the following ?

class AppColors {
  Color get primary => const Color(0xFFFF0000);

class AppThemeState extends State<AppTheme> {
  final AppColors colors = AppColors();

Is that okay or a bad practice and there are better ways to do this ? That "extends State" is just because i'm creating an InheritedWidget to access theme by context. I know about Maps in Dart but notice that i want an access by dot (.primary) not by index (['primary']).

asked on Stack Overflow Oct 27, 2019 by Andrei • edited Oct 27, 2019 by Andrei

1 Answer


You don't have to do that. In flutter you can do this by utilizing main.dart. And then calling the primaryColor from that will give you the desired color which you've defined in your main.


  Widget build(BuildContext context) {
    print("in the main builder");

    return MaterialApp(
      title: 'The Monk',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: 'your_desired_color'

Then you can use your primary color by this line anywhere in your widgets/components -> Theme.of(context).primaryColor. This will solve your problem and is the efficient way of doing this in Flutter. Thanks

answered on Stack Overflow Oct 27, 2019 by Alok

User contributions licensed under CC BY-SA 3.0