Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to TextField changes realtime and update a Text widget with TextField content?

I have a TextField and a Text widget that should show in RealTime the text written in the TextField.

This is the code:

 late final TextEditingController _importo;

  @override
  void initState() {
    _importo = TextEditingController();
    super.initState();}

    @override
    Widget build(BuildContext context) {
      return Column(children: [
        SizedBox(
          width: 50,
          child: TextField(
            textAlign: TextAlign.end,
            controller: _importo,
            decoration: const InputDecoration(
              hintText: '0.00',
            ),
            autocorrect: false,
            keyboardType: TextInputType.number,
          ),
        ),
        Text(
          _importo.text,
          style: const TextStyle(
            fontWeight: FontWeight.w400,
            fontSize: 15,
          ),
        ),
      ]);
    }
  }

I think there is something missing because the Text widget isn't updating.

like image 451
faccio Avatar asked Oct 27 '25 08:10

faccio


1 Answers

In text field in change event set state

TextField (
 onChanged:(val){
   setState((){});
  }
)

EDIT

import 'package:flutter/material.dart';



void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
     
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  TextEditingController _textController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
       children: [
         Container(
           color: Colors.grey.withOpacity(0.2),
           child: Text("${_textController.text}")),
         SizedBox(height: 20),
         Container(
           color: Colors.grey,
           child: TextField(
             
             controller: _textController,
             onChanged: (val){
               setState((){});
             }
           ),
         )
       ]
      ),
    );
  }
}

preview

like image 144
Kaushik Chandru Avatar answered Oct 28 '25 23:10

Kaushik Chandru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!