How do I update a Widget via a controller in an Onchanged field?

Asked

Viewed 290 times

0

I cannot update a Text widget that should show the sum of two Textformfield as long as someone is changing it (Onchanged). What could I be doing wrong? (I’ve put Setstate everywhere and nothing has worked)

Below, one of Textformfield:

child: TextFormField(
                            onChanged: (value) {
                              setState(() {
                                _ComprPeca = value;
                              });
                            },
                            controller: myController,
                            keyboardType: TextInputType.number,
                            decoration: InputDecoration(
                                labelText: 'Comprimento da Peça'),
                          ),

The container that has Text that I want to change:

Container conteiner = Container(
      child: Padding(
          padding: const EdgeInsets.all(20),
          child: Expanded(child: Text(_ComprPeca + _ComprLanca))));

The Controller I will leave:

  final myController = TextEditingController();
  @override
  void initState() {
    super.initState();
    myController.addListener(_printLatestValue);
  }

    @override
  void dispose() {
    // Clean up the controller when the widget is removed from the widget tree.
    // This also removes the _printLatestValue listener.
    myController.dispose();
    super.dispose();
  } 

  _printLatestValue() {
    print("Second text field: ${myController.text}");
    print("comprimento lanca: " + _ComprLanca);
    setState(() {});
  }

1 answer

1


As you are already working with a TextEditingController, no need to pick up the text directly by OnChanged(), This should solve your problem:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) => MaterialApp(
    home: MyHomePage(),
  );
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  TextEditingController controller_1 = TextEditingController();
  TextEditingController controller_2 = TextEditingController();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Text(
            (
              (double.tryParse(controller_1.text)??0) + 
              (double.tryParse(controller_2.text)??0)
            ).toString()),
          TextField(
            controller: controller_1,
            decoration: InputDecoration(
              hintText: "Campo 1"
            ),
            onChanged: (String value) {
              setState((){});
            },
          ),
          TextField(
            controller: controller_2,
            decoration: InputDecoration(
              hintText: "Campo 2"
            ),            
            onChanged: (String value) {
              setState((){});
            },
          )
        ],
      )
    );
  }
}

Explaining

Like the controller returns what was typed in TextField as String you need to make the conversion to Integer or Double. In my example I did the conversion of values to Double as follows:

(double.tryParse(controller_2.text)?? 0)

I did so so so that if you type some character other than a number your application does not lock.

The tryParse as its name says, tries to convert the value to double and if it does not succeed it returns NULL. And if it returns NULL I have already dealt with the ?? 0 which turns the NULL return to 0 (Zero).

You can test the operation by Dartpad, just copy and paste there.

  • 1

    From what I understand the author of the question wants to know how to sum two typed numbers and display in a Text. In this case I think it is interesting to mention the conversion from String to Double and (maybe) the use of multiple controllers.

  • @Naslausky Reading again, really I had misunderstood... But I have already adjusted the answer according to your tip.

  • 1

    Perfect people! My problem was in the fact that when I added up the two values, if one of them was empty the sum did not happen. And I could only realize this after I put a Try Catch into that sum, the debug didn’t take this error and let everything work normally. I did so and managed to solve: Try { _Resultsdouble = (_Comprlanca.isEmpty ? 0.0: double.parse(_Comprlanca)) *1.25 +double.parse(_Comprpeca) / 2;} catch (e) {print(e); } Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.