skip to Main Content

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


  1. 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> {
      late final TextEditingController _controller;
    
      @override
      void initState() {
        _controller = TextEditingController();
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter Number Incrementer'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                /// Here, wrap your TextWidget with  ///ValueListenableBuilder<TextController>.
                ///It's automatically rebuild when change the TextEditingValue linked TextEditingController
                ///
                ValueListenableBuilder(
                  valueListenable: _controller,
                  builder: (BuildContext context, TextEditingValue value, Widget? child) {
                    return Text(
                      ///
                      /// "Hello it's a constant text"
                      /// Just value changes when you change the TextEditingController
                      /// 
                      "Hello ${value.text}",
                      style: TextStyle(fontSize: 20),
                    );
                  },
                ),
    
                SizedBox(height: 20),
                TextField(
                  controller: _controller,
                  keyboardType: TextInputType.number,
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () {
                      int currentValue = (int.tryParse(_controller.text) ?? 0) + 1;
    
                      _controller.text = currentValue.toString();
                      _controller.notifyListeners();
                  },
                  child: Text('Increment'),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. Add listener to a controller in initstate(). This will update the widget using setstate() whenever textfield is updated or detect changes.

    class _MyHomePageState extends State<MyHomePage> {
     TextEditingController _controller = TextEditingController();
     String _helloText = 'Hello 0';
    
     @override
     void initState() {
       super.initState();
       _controller.addListener(_updateHelloText);
     }
    
     void _updateHelloText() {
       setState(() {
         _helloText = 'Hello ${_controller.text}';
       });
     }
    
    @override
    void dispose() {
     _controller.removeListener(_updateHelloText);
     _controller.dispose();
     super.dispose();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search