【发布时间】:2020-05-23 01:47:46
【问题描述】:
我正在尝试创建一个按钮,当按下该按钮时,它将在测量单位(即厘米和英寸)之间循环来回摆动。我可以从厘米到英寸,但如果按下按钮并显示英寸,我不知道如何使文本动态变回厘米。我知道我需要将 if 语句从我的 setState 中移出,但似乎无法让它在没有错误的情况下正常工作。有什么建议吗?
import 'package:flutter/material.dart';
enum Units { cm, inches }
class InputRow extends StatefulWidget {
InputRow({
this.inputParameter,
});
final String inputParameter;
@override
_InputRowState createState() => _InputRowState();
}
class _InputRowState extends State<InputRow> {
String Unit = 'cm';
Units selectedUnit;
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
SizedBox(
height: 100,
),
Container(
constraints: BoxConstraints(maxWidth: 350),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(widget.inputParameter),
Flexible(
child: TextField(),
),
Text(Unit),
RaisedButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.red)),
color: Colors.deepPurple,
textColor: Colors.black,
onPressed: () {
setState(() {
selectedUnit == Units.inches ? Units.cm : Units.inches;
if (selectedUnit == Units.cm) {
Unit = 'cm';
} else {
Unit = 'inches';
}
});
},
),
],
),
)
],
));
}
}
【问题讨论】:
-
String Unit应该存储在小部件的状态中。 -
克里斯,即使我将它移动到小部件的状态内(即在类 _InputRowState 下)它仍然没有重置
-
请发布您的更新代码。
-
更新了原帖
-
selectedUnit未初始化。此外,变量应使用lowerCamelCase命名。