我是新的flutter,在学习阶段。在创建一个简单的flutter应用程序的过程中,该应用程序通过分配A=1到Z=26来计算输入到textformfield中的文本/数字的值到个位数
例如:如果输入为Hello,则输出应为7;如果输入为hello 2,则输出应为9
我试过低于代码,但是
1.它不是计算到个位数,
1.它不是计算数字,
1.当文本框为空时,如果我点击计算按钮,则显示计算的旧值
class _ValueCalculatorState extends State<ValueCalculator> {
final TextEditingController _inputText = TextEditingController();
final TextEditingController _resultsText = TextEditingController();
String results = "0";
String value = "";
String inputText = "";
void clearTextField() {
_inputText.clear();
_resultsText.clear();
setState(() {});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Scaffold(
body: SingleChildScrollView(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
children: [
TextFormField(
controller: _inputText,
minLines: 5,
maxLines: 9,
keyboardType: TextInputType.multiline,
onChanged: (name) {
inputText = name;
//value1 = name;
},
decoration: InputDecoration(
labelText: 'Enter Text ',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
),
const Padding(
padding: EdgeInsets.symmetric(
vertical: 20.0,
horizontal: 20.0,
),
),
Text(
results,
style: TextStyle(fontSize: 50),
),
const Padding(
padding: EdgeInsets.symmetric(
vertical: 20.0,
horizontal: 20.0,
),
),
ElevatedButton(
onPressed: () {
// calculation logic\
value = inputText.replaceAll(RegExp('[^A-Za-z0-9]'), '');
int sum = 0;
if (value.trim().isNotEmpty) {
for (int i = 0; i < value.length; i++)
(value[i].toUpperCase() == value[i])
? sum += (value.codeUnitAt(i) - 64)
: sum += (value.codeUnitAt(i) - 96);
setState(() {
results = sum.toString();
});
}
print(sum);
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 25,
horizontal: 60,
),
),
child: const Text("Calculate"),
),
const Padding(
padding: EdgeInsets.symmetric(
vertical: 20.0,
horizontal: 20.0,
),
),
ElevatedButton(
onPressed: () {
clearTextField();
results = "0";
},
child: Text("Reset"),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 15,
horizontal: 30,
),
),
),
],
),
),
),
),
),
);
2条答案
按热度按时间v6ylcynt1#
我希望你会觉得这对你有帮助
wbrvyc0a2#
更新计算按钮的onPressed()方法,如下所示:它将解决这两个问题,考虑数字和空字符串显示0