gpt4 book ai didi

flutter - 如何从用户那里获取 2 个输入并执行计算并在 flutter 应用程序中显示结果

转载 作者:行者123 更新时间:2023-12-02 02:04:19 25 4
gpt4 key购买 nike

我对 flutter 还很陌生,我正在创建一个简单的应用程序来计算一些指标。所以我应该从用户那里获取 2 个输入值并进行数学计算并将结果显示在应用程序中。我了解到我可以使用 TextField 小部件获取输入。那么,一旦我使用 TextField 小部件获得输入,如何执行数学计算并显示结果?帮我解决这个问题。

最佳答案

尝试下面的代码希望它能解决您的问题,在下面的代码中我执行了加法、减法、乘法和除法运算。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appTitle = 'Add Two Numbers';

return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: Text(appTitle),
),
body: AddTwoNumbers(),
),
);
}
}

class AddTwoNumbers extends StatefulWidget {
@override
_AddTwoNumbersState createState() => _AddTwoNumbersState();
}

class _AddTwoNumbersState extends State<AddTwoNumbers> {
TextEditingController num1controller = new TextEditingController();
TextEditingController num2controller = new TextEditingController();
String result = "0";
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextField(
keyboardType: TextInputType.number,
controller: num1controller,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'First Number',
hintText: 'Enter First Number',
),
),
SizedBox(
height: 20,
),
TextField(
keyboardType: TextInputType.number,
controller: num2controller,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Second Number',
hintText: 'Enter Second Number',
),
),
SizedBox(
height: 20,
),
Wrap(
children: [
ElevatedButton(
child: Text("Addition"),
onPressed: () {
setState(() {
int sum = int.parse(num1controller.text) +
int.parse(num2controller.text);
result = sum.toString();
});
},
),
SizedBox(
height: 20,
width: 20,
),
ElevatedButton(
child: Text("Subtraction"),
onPressed: () {
setState(() {
int sum = int.parse(num1controller.text) -
int.parse(num2controller.text);
result = sum.toString();
});
},
),
SizedBox(
height: 20,
width: 20,
),
ElevatedButton(
child: Text("Multiplication"),
onPressed: () {
setState(() {
int sum = int.parse(num1controller.text) *
int.parse(num2controller.text);
result = sum.toString();
});
},
),
SizedBox(
height: 20,
width: 20,
),
ElevatedButton(
child: Text("Division"),
onPressed: () {
setState(() {
int sum = int.parse(num1controller.text) ~/
int.parse(num2controller.text);
result = sum.toString();
});
},
),
],
),
SizedBox(
height: 20,
),
Text('Result : $result'),
],
),
);
}
}

您的屏幕如下:enter image description here

关于flutter - 如何从用户那里获取 2 个输入并执行计算并在 flutter 应用程序中显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68655773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com