Reputation: 1042
I have a Text()
widget and a TextFormField()
widget with TextInputType.number
. What I want is when a user is typing in the TextFormField()
subtraction math should be happening in real-time.
The value entered in the TextFormField()
should subtract the value inside the Text()
widget automatically as the user is typing numbers inside the TextFormField()
;
Note The final result should be shown in the same Text()
widget as all of this typing and subtraction is happening.
import 'package:flutter/material.dart';
class ChangeValuesPage extends StatefulWidget {
@override
_ChangeValuesPageState createState() {
return _ChangeValuesPageState();
}
}
class _ChangeValuesPageState extends State<ChangeValuesPage> {
final pureNumbers = RegExp(r'^[0-9]+$');
int numberValue = 200;
int latestNumberValue;
final formKey = new GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: appbar(context, 'Simple App', 'otherData'),
drawer: TopDrawer(),
body: SingleChildScrollView(
child: new Card(
child: Padding(
padding: EdgeInsets.all(5.0),
child: new Column(
children: <Widget>[
/**
* Below is the Text() field where subtraction math should occure.
*/
/// The value in the Text() widget should be subtracted automatically with
/// the number values inside the TextFormField() widget automatically as the user is typing the numbers
Text(
'Number value text: ${this.numberValue}',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(
height: 6,
),
new Form(
key: formKey,
child: new Column(
children: <Widget>[
TextFormField(
keyboardType: TextInputType.number,
decoration: new InputDecoration(
labelText: 'Reduce number value?',
hintText: 'Default number value is "0"',
),
validator: (val) {
if (val.isEmpty == true) {
return 'Fill in number values';
}
if (pureNumbers.hasMatch(val) == false) {
return 'Use alphanumeric characters only in nickname';
}
return null;
},
onSaved: (val) => this.latestNumberValue = int.parse(val),
),
],
),
),
],
),
),
),
),
);
}
}
I have tried different ways to achieve this but nothing is working. Thank you, posted with Love.
Upvotes: 0
Views: 2779
Reputation: 2864
Try implementing this for onChanged
property of the TextFormField
. Hope this is what you are trying to achieve.
onChanged: (val) {
if (val.isEmpty) {
setState(() => numberValue = 200);
} else {
numberValue = 200;
setState(() => numberValue -= int.parse(val));
}
},
Upvotes: 2