【发布时间】:2020-11-30 12:02:32
【问题描述】:
我需要你的帮助,
我想将不同文本字段的值相乘。我面临*不能与TexteditingController()一起使用的问题:
void _calculation() {
_volume = lenCon * widCon * higCon;
print(_volume);
}
我是否需要将 lenCon 之类的变量转换为之前的两倍?我怎样才能做到这一点? var lenConInt = double.parse(lenCon); 不起作用。
RaisedButton 必须执行_calculation 并使用正确的值更改文本。我需要一个 StatlessWidget 还是 SetState?
提前致谢!
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _volume = 0;
// var _lenght;
// var _width;
// var _hight;
void _calculation() {
_volume = lenCon * widCon * higCon;
print(_volume);
}
final lenCon = new TextEditingController();
final widCon = new TextEditingController();
final higCon = new TextEditingController();
// var lenConInt = double.parse(lenCon);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: lenCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Länge',
),
),
TextField(
controller: widCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Breite',
),
),
TextField(
controller: higCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Höhe',
),
),
RaisedButton(
onPressed: (_calculation),
child: Text('Berechnen'),
),
Text('Your Volume is: $_volume'),
],
),
),
),
);
}
}
【问题讨论】:
-
try
var lenConDouble = double.parse(lenCon.text);.text从 TextEditingController flutter.dev/docs/cookbook/forms/retrieve-input 检索输入的值 -
我建议您阅读 Stateless Widget 和 Stateful Widget 之间的区别;)
-
@sonic 在这里使用有状态小部件是正确的,因为他想在计算后更新最后一个 Text 小部件。但是,状态未正确初始化。
-
@Heikkisorsa 我并不是说在这里使用有状态小部件是错误的。我只是指着这个问题“我需要一个 StatlessWidget 还是 SetState?”我即将回答:“回答自己你真正需要使用什么以及为什么”
-
@sonic 你说得对,我要学很多东西!