After clicking the button to update _formData, why does the page not display the new value?
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
const TestPage({Key? key}) : super(key: key);
@override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
Map<String, String> _formData = {
'id': '',
'title': '',
'desc': '',
};
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
FilledButton(
onPressed: () {
setState(() {
_formData['title'] = _getText();
});
},
child: Text('test')),
TextFormField(
decoration: const InputDecoration(labelText: 'Title'),
initialValue: _formData['title'],
onSaved: (val) => _formData['title'] = val!,
),
TextFormField(
decoration: const InputDecoration(labelText: 'Description'),
initialValue: _formData['desc'],
onSaved: (val) => _formData['desc'] = val!,
),
],
));
}
}
String _getText() {
return DateTime.now().toString();
}
I need to fill in the selected product information into this form, there are about 20 fields, so I hope to use setData instead of the controller.
2
Answers
some changes in code, try below code :
it seems like that
TextFormField
will not be updated after you callsetState()
, use_formData['title']
as a key ofTextFormField
like belowthen
TextFormField
will be updated every time you update_formData['title']