Kshitij Dhakal
Kshitij Dhakal

Reputation: 844

How to pass Widget to const Constructor in flutter?

I have a class to store title, body and icon of tabs in my flutter app.

class Destination {
  const Destination(
      {this.title,
      this.icon,
      this.color = Colors.blue,
      this.body: const Center(
        child: Text("Example"),
      )});

  final String title;
  final IconData icon;
  final MaterialColor color;
  final Widget body;
}

and I am trying to create list of all my tabs using

const List<Destination> allDestinations = <Destination>[
  Destination(title: 'Calculate', icon: Icons.edit, body: const Calculator()),
  Destination(
    title: 'Detail',
    icon: Icons.details,
  )
];

But it keeps showing error that const variables must be initialized with constant value whether I add const or not. Calculator() is just StatefulWidget. So I would appreciate any help to understand what I'm doing wrong.

Upvotes: 0

Views: 4916

Answers (2)

Mehmet Esen
Mehmet Esen

Reputation: 6896

As I said, Calculator does not have const constructor. Sometimes you can't make the const constructors for Widgets. Because the Widget must be immutable class which may break your purpose.

In Flutter some widgets have const constructor some of them don't have(etc. Column, Row, AnimatedContainer). Usually the reason is they are interactive(both inside and outside).

One another trick in your example, if you put const to your variable, the right side of assignment does not need any const. Because if this variable is const, right side must be const already so no need to define const each time.

Same thing valid for also trees, if parent has const, child must be const, no need to put another const.

In your example, if Calculator had a const constructor, putting const to Calculator won't make any difference.

So this has exact same functionality with yours:

const List<Destination> allDestinations = <Destination>[
  Destination(title: 'Calculate', icon: Icons.edit, body: Calculator()),
  Destination(
    title: 'Detail',
    icon: Icons.details,
  )
];

Upvotes: 3

lazos
lazos

Reputation: 1075

What if you make Calculator constructor const:

class Calculator extends StatefulWidget {
  const Calculator({Key key}) : super(key: key);

  @override
  _CalculatorState createState() => _CalculatorState();
}

Upvotes: 2

Related Questions