如何在Flutter中添加几个表单字段的值以动态计算总字段?想象一下如果三个文本字段的值分别为1、2、3,则总字段应显示为6。
我可以使用double.parse(value)
将值转换为两倍。
代码:
class _GivingPageState extends State<GivingPage> {
final _formKey = GlobalKey<FormState>();
double collection1;
double collection2;
double collection3;
double total;
@override
void initState() {
collection1 = 0;
collection2 = 0;
collection3 = 0;
total = 0;
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Column(
children: <Widget>[
Expanded(
child: buildContent(),
),
],
),
),
),
);
}
Widget buildContent() {
return Container(
color: Colors.white,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: lightCard(
child: Container(
padding: EdgeInsets.only(left: 0.0, right: 10, top: 10, bottom: 10),
child: Padding(
padding: const EdgeInsets.only(left: 18.0, bottom: 10),
child: Container(
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 0.0, bottom: 10),
child: Text(
'Collection Baskets',
style: TextStyle(
fontSize: 16, fontWeight: FontWeight.bold),
),
),
Text('Which collection baskets(s) are you giving to?'),
SizedBox(height: 15),
_buildBasket(
collectionName: 'Amount 1',
collection: collection1,
),
SizedBox(height: 10),
_buildBasket(
collectionName: 'Amount 2',
collection: collection2,
),
SizedBox(height: 10),
_buildBasket(
collectionName: 'Amount 3',
collection: collection3,
),
SizedBox(height: 10),
_buildTotal()
],
),
),
),
),
)),
));
}
void _updateTotal() {
setState(() {
total = collection1 + collection2 + collection3;
});
}
Row _buildBasket(
{@required String collectionName, @required double collection}) {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Text(
collectionName,
style: TextStyle(fontSize: 16),
),
),
SizedBox(width: 10),
Expanded(
flex: 1,
child: Row(
children: <Widget>[
Text(
'£',
style: TextStyle(fontSize: 20),
),
SizedBox(width: 10),
Expanded(
child: numberFormField(
onChanged: (value) {
setState(() {
collection = double.parse(value);
_updateTotal();
});
},
textFieldKey: null),
),
],
),
),
],
);
}
Row _buildTotal() {
return Row(
children: <Widget>[
Expanded(
flex: 1,
child: Text(
'Total',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
SizedBox(width: 10),
Expanded(
flex: 1,
child: Row(
children: <Widget>[
Text(
'£',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
SizedBox(width: 10),
Expanded(
child: Container(
height: 50,
decoration: BoxDecoration(
color: AppColors.secondaryElement,
borderRadius: Radii.k25pxRadius,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"${formatNumber(amount: total)}",
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20),
),
],
),
),
),
],
),
),
],
);
}
}
答案 0 :(得分:1)
这对您有用吗?
recipe