Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 451
washcloth Avatar asked Dec 07 '25 11:12

washcloth


1 Answers

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(
   ...
)
like image 183
Rémi Rousselet Avatar answered Dec 10 '25 01:12

Rémi Rousselet