I have a beginner question.
I don't understand why TextFormField is not updated in this example on pressing the FloatingActionButton. _counter field is incremented inside of setState. Text widget is updated as expected.
I see this difference: Text is stateless and TextFormField statefull widget.
What should I do to show the correct value also inside TextFormField?
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Your number:',
),
TextFormField(
keyboardType: const TextInputType.numberWithOptions(
signed: false,
decimal: false,
),
initialValue: (_counter.toString()),
onChanged: (val) {
setState(() {
_counter = int.parse(val);
});
},
),
Text(
'$_counter',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Thank you
Qjeta