Home > Net >  Flutter Define Map Multi-dimensional structure including Key Names
Flutter Define Map Multi-dimensional structure including Key Names

Time:11-08

I'm trying to create a custom navigation widget. This essentially involves a Map where the key is the route. One's the key is defined instead of the value simply being the page I want some additional data, not just a page widget.

For each map value I want to require a:

String pageType;
Dynamic altColor;
Widget pageContent

I have been able to achieve this by placing a sub map inside the map but this does not allow me to define the data types and keys I want.

class UINav extends StatelessWidget {
  UINav({required this.routes})
  final Map<String, Map<String, dynamic>> routes;
...

Basically each map element should require each of the above rather than being open to any data.

CodePudding user response:

Try this:

class NavTarget {
  NavTarget(
      {required this.pageType,
      required this.altColor,
      required this.pageContent});
  String pageType;
  dynamic altColor;
  Widget pageContent;
}

And then:

final Map<String, NavTarget> routes = {
      'first': NavTarget(
          pageType: 'pageType1',
          altColor: 'altColor1',
          pageContent: const Text('pageContent1')),
      'second': NavTarget(
          pageType: 'pageType2',
          altColor: 'altColor2',
          pageContent: const Text('pageContent2')),
    };
print(routes['first']!.altColor);
  • Related