如何使用flutter中的textfield制作一个数字计数器应用程序


import 'package:flutter/material.dart';
void main() => runApp(Spent());
class Spent extends StatefulWidget {
@override
SpentState createState() => SpentState();
}
class SpentState extends State<Spent> {
final _controller = TextEditingController();
String name = '';
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container (
padding: const EdgeInsets.all(30.0),
child: Container(
child:  Center(
child:  Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(name),
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
decoration:  InputDecoration(
fillColor: Colors.black,
border:  OutlineInputBorder(
borderRadius:  BorderRadius.circular(25.0),
borderSide: BorderSide(),
),
),
keyboardType: TextInputType.number
),
FlatButton(
child: Text("Enter"),
onPressed: () {
setState(() {
name = _controller.text;
});
},
)
]
)
),
)
)
)
);
}
}

像这样,我有一个TextFormField。我希望我的应用程序使用textfield减去当前存在的数字。例如,如果我有数字5000,用户会键入2000并按enter键。这将使数字达到3000。我该怎么做?

这里有一个可能的解决方案,包含基本的错误检查。

class SpentState extends State<Spent> {
final _controller = TextEditingController();
double value = 5000;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
padding: const EdgeInsets.all(30.0),
child: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(value.toString()),
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
decoration: InputDecoration(
fillColor: Colors.black,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(),
),
),
keyboardType: TextInputType.number),
FlatButton(
child: Text("Enter"),
onPressed: () {
//check if we can parse it
if (double.tryParse(_controller.text) == null)
return; //can't parse it
double enteredValue =
double.parse(_controller.text);
setState(() {
value -= enteredValue;
});
},
)
])),
))));
}
}

最新更新