为什么我不能在flutter中输入用于title的变量?

时间:2018-12-02 19:48:37

标签: android dart flutter

在扑朔迷离中,您无法设置title变量进行测试,因为Text不会是恒定的。

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'),
              ),
            ],
          ),
        ),
      )
    );
  }

}

我将如何实现这一目标?为什么颤振不允许这种情况发生?

1 个答案:

答案 0 :(得分:2)

之所以发生这种情况,是因为您尝试将父项ListTile实例化为const

但是要使ListTileconst,它也需要其子Text为const,因此不能有变量。 只需将ListTile更改为 not const

ListTile(
   ...
)