washcloth
washcloth

Reputation: 2896

Why can't I take in a variable for title in flutter?

In flutter you can't set the title variable to test because Text would not be constant.

class StockCard extends StatelessWidget {

  String test;

  StockCard(String t) {
    test = t;
  }

  @override
  Widget build(BuildContext context) {
    return (
      new Container(
        margin: const EdgeInsets.all(10.0),
        child: new Card(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const ListTile(
                leading: Icon(Icons.trending_up),
                title: Text(test), // ERROR: error: Evaluation of this constant expression throws an exception.
                subtitle: Text('Apple Incorporated'),
              ),
            ],
          ),
        ),
      )
    );
  }

}

How would I achieve this and why does flutter not allow this to happen?

Upvotes: 3

Views: 2739

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277027

This happens because you try to instantiate the parent ListTile as const.

But for ListTile to be const, it requires its child Text to be const too, therefore cannot have a variable. Just change ListTile to not be const:

ListTile(
   ...
)

Upvotes: 9

Related Questions