everyone.
I am using Form and TextFieldForm without any own TextEditController. Have 3 TextFieldForm (Value_1, Value_2, Total) with initial values. When i am editing first one, the Total textfield should contain result of calculation . To update widget i am using setState. The problem that variable _total and Text widget always has a correct calculation value, but the Total textfield does not want to update.
why? is it posible to do without using own TextEditController?
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TestForm(),
);
}
}
class TestForm extends StatefulWidget {
@override
_TestFormState createState() => _TestFormState();
}
class _TestFormState extends State<TestForm> {
GlobalKey<FormState> _formKey = GlobalKey();
int _value1 = 0;
int _value2 = 20;
int _total = 0;
@override
Widget build(BuildContext context) {
print('rebuild');
return Scaffold(
appBar: AppBar(title: Text('test form')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
TextFormField(
initialValue: _value1.toString(),
decoration: InputDecoration(
labelText: 'Value_1',
),
keyboardType: TextInputType.number,
onChanged: (value) {
setState(() {
_total = int.parse(value) * _value2;
print('total: ' + _total.toString());
});
},
),
TextFormField(
initialValue: _value2.toString(),
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Value_2',
),
),
TextFormField(
initialValue: _total.toString(),
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Total',
),
),
SizedBox(height: 20),
Text('total: ' + _total.toString()),
],
),
),
),
);
}
}
If you have a reactive data source, aka data that can change based on either network updates or other data, one hack that worked for me was to use a Key
.
By making a Key
of the reactive data (toString()
), the form field will change every time the Key
changes.
So in this case you could do:
TextFormField(
key: Key(_total.toString()), // <- Magic!
initialValue: _total.toString(),
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Total',
),
),
I used something as simple as this:
TextFormField(
controller: TextEditingController()..text = '23232',
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Total',
),
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With