How to update the text widget with change in textfield. I want the text to change text where ever there is a change in textfield either due to user input or due to button updating textfield.
I have used onChange but it only updated text widget on user put change but not on button click. I do not want on button click to updated text widget. In my actual scenario there can be multiple events that can updated text field. So only on text field change I want text widget to update.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _controller = TextEditingController();
String _helloText = 'Hello 0';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Number Incrementer'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_helloText,
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
TextField(
controller: _controller,
keyboardType: TextInputType.number,
onChanged: (value) {
// Update the "Hello" text whenever the value in the TextField changes
setState(() {
_helloText = 'Hello $value';
});
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
// On button click, increment the number in the TextField
setState(() {
int currentValue = int.tryParse(_controller.text) ?? 0;
currentValue++;
_controller.text = currentValue.toString();
});
},
child: Text('Increment'),
),
],
),
),
);
}
}
2
Answers
Add listener to a controller in initstate(). This will update the widget using setstate() whenever textfield is updated or detect changes.