我想知道如何将字符串从类传递到其状态类。
我尝试使用widget.foodName
将字符串传递到Text小部件中,但是它返回了错误“此常量表达式的计算引发异常”。
我猜想因为构造函数正在声明该字符串,所以它将返回该问题。
有什么想法可以解决这个问题吗?
import 'package:flutter/material.dart';
class FoodCard extends StatefulWidget {
@override
FoodCard(this.chosenIcon, this.foodName, this.expireDate);
int chosenIcon;
String foodName;
String expireDate;
_FoodCardState createState() => _FoodCardState();
}
class _FoodCardState extends State<FoodCard> {
@override
Widget build(BuildContext context) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.apps),
title: Text(widget.foodName), // <<<--------------
subtitle: Text("xyz"),
)
],
),
);
}
}
答案 0 :(得分:1)
将您的FoodCard
类更改为以下结构,您将可以毫无问题地调用foodName
属性。这些更改是根据Stateful
小部件类documentation进行的:
class FoodCard extends StatefulWidget {
FoodCard({Key key, this.chosenIcon, this.foodName, this.expireDate}): super(key: key);
final int chosenIcon;
final String foodName;
final String expireDate;
@override
_FoodCardState createState() => _FoodCardState();
}
您还应该删除const
小部件之前添加的ListTile
:
class _FoodCardState extends State<FoodCard> {
@override
Widget build(BuildContext context) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Icon(Icons.apps),
title: Text(widget.foodName), // <<<--------------
subtitle: Text("xyz"),
)
],
),
);
}
}