TETTASUN
TETTASUN

Reputation: 125

How to assign class type to variables on dart

I'm new to flutter and dart.

I want to transition with drawer like below.

class Page {
  String title;
  var page;
  Page(this.title, this.page);
}

class CommonDrawer extends StatelessWidget {
  var _pages = [Page('Home', HomePage),
              Page('Form', FormPage)];

  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: ListView(
      children: <Widget>[
        for (final p in _pages) genTile(p, context),
      ]

  ListTile genTile(Page page, context) {
      ~~~~~~~ Omitted ~~~~~~~~~~
      Navigator.push(
        context, MaterialPageRoute(builder: (context) => page.page()));
  }
}

but console says

Attempted to use type 'FormPage' as a function. Since types do not define a method 'call', this is not possible. Did you intend to call the FormPage constructor and forget the 'new' operator?

new page.page() is compile error.

Do anyone know right way of this on dart?

Upvotes: 1

Views: 3073

Answers (1)

lrn
lrn

Reputation: 71653

You cannot abstract over classes in Dart. With type variables (generics), you can abstract over types, but even that won't allow you to call constructors.

Try changing the code to:

class Page {
  String title;
  dynamic Function() createPage;
  Page(this.title, this.createPage);
}

class CommonDrawer extends StatelessWidget {
  var _pages = [Page('Home', () => HomePage()),
              Page('Form', () => FormPage())];
...
      Navigator.push(
        context, MaterialPageRoute(builder: (context) => page.createPage()));
  }
}

(I'd use a different type than dynamic for the return type of createPage, but I can't see what the common supertype of HomePage and FormPage is).

Upvotes: 1

Related Questions