George Morris
George Morris

Reputation: 484

Initialize a dart class from a variable

Let's consider we have a list of pages and based on some logic, we want to display the corresponding route using Navigator. How do we do that?

final List<dynamic> components = [ PageA, PageB ]
..
Navigator.push(
  context,
  MaterialPageRoute(
      builder: (context) =>  new components[0]()),
);

Upvotes: 0

Views: 147

Answers (2)

Aashar Wahla
Aashar Wahla

Reputation: 3295

There is routes attribute within material app widget. You should use that:

MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Sample',
      home: Wrapper(),
      routes: {
        CarsList.routeName: (ctx) => PageOne(),
        CarDisplay.routeName: (ctx) => PageTwo(),
        OrdersScreen.routeName: (ctx) => PageThree(),
        EditCar.routeName: (ctx) => PageFour(),
      },
    ),

Before using that make sure that you have a static variable named as routeName in every widget.

static const routeName = '/PageOne';

Upvotes: 3

Lulupointu
Lulupointu

Reputation: 3584

I'm not entirely sure I understand you issuer but if your question is where/how you can put a condition there are two ways of doing so:

Let's say that based on condition you when to navigate to either components[0]() or components[1]() :

First:

final List<dynamic> components = [ PageA, PageB ]
..
Navigator.push(
  context,
  MaterialPageRoute(
      builder: (context) =>  condition ? new components[0]() : new component[1]()
  ),
);

Second:

 final List<dynamic> components = [ PageA, PageB ]
    ..
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) {  
          if (condition) {
              return new components[0]()
          } else {
              return new component[1]()
          }
      ),
    );

Upvotes: 0

Related Questions