Search code examples
flutterflutter-textformfieldflutter-textinputfield

Flutter: Dynamically Updating TextField Values Based on User Input


I am currently working on my Flutter application and I am encountering difficulties in achieving a specific functionality. The objective is to automatically populate and disable the third TextField on a page that consists of three TextFields, once any two of the TextFields have been filled. Additionally, when at least one of the filled TextFields is cleared, the disabled TextField should be re-enabled.

To illustrate with examples:

enter image description here

In the first scenario, upon entering data in both the first and second fields, the third field should become disabled, and its value should be the product of the values entered in the first and second fields. Consequently, whenever input is entered in either the first or second field, the value of the third field should be updated accordingly.

enter image description here

In another scenario, if data is entered in the first and third fields, the second field should be disabled and its value should be updated automatically. Similarly, I would like the first field to exhibit the same behavior when input is entered in the second and third fields.

I attempted to create a function utilizing the TextEditingController and the onChanged function of the TextField, but I have been unsuccessful in achieving continuous updates to the TextField value. Therefore, I would greatly appreciate any assistance in this matter.

Thank you in advance for your support.


Solution

  • You can use TextEditingController and flag var combination to achieve what you need. there are so many other ways too. below i added working example implementation.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
            useMaterial3: true,
          ),
          home: const MathScreen(),
        );
      }
    }
    
    class MathScreen extends StatefulWidget {
      const MathScreen({super.key});
    
      @override
      State<MathScreen> createState() => _MathScreenState();
    }
    
    class _MathScreenState extends State<MathScreen> {
      bool t1 = true;
      bool t2 = true;
      bool t3 = true;
    
      TextEditingController t1Controller = TextEditingController();
      TextEditingController t2Controller = TextEditingController();
      TextEditingController t3Controller = TextEditingController();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SafeArea(
            child: Padding(
              padding: const EdgeInsets.all(32.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    child: Row(
                      children: [
                        Expanded(
                          child: TextField(
                            enabled: t1,
                            keyboardType: TextInputType.number,
                            controller: t1Controller,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(30.0),
                              ),
                              filled: true,
                              hintStyle: TextStyle(
                                color: Colors.grey[800],
                              ),
                              hintText: "",
                              label: Text("Amount"),
                              fillColor: Colors.white70,
                            ),
                            onChanged: (value) {
                              if ((t3Controller.text == "" || !t3) &&
                                  (t2Controller.text != "")) {
                                setState(() {
                                  t3 = false;
                                  t1 = true;
                                  t2 = true;
                                  t3Controller.text = value == ""
                                      ? ""
                                      : (num.parse(value) *
                                              num.parse(t2Controller.text))
                                          .toString();
                                });
                              }
                              if (t3Controller.text != "" &&
                                  (t2Controller.text == "" || !t2)) {
                                setState(() {
                                  t2 = false;
                                  t1 = true;
                                  t3 = true;
                                  t2Controller.text = value == ""
                                      ? ""
                                      : (num.parse(t3Controller.text) /
                                              num.parse(value))
                                          .toString();
                                });
                              }
                              if (t2Controller.text == "" &&
                                  t1Controller.text == "" &&
                                  t3Controller.text == "") {
                                setState(() {
                                  t2 = true;
                                  t1 = true;
                                  t3 = true;
                                });
                              }
                            },
                          ),
                        ),
                        Text(" X "),
                        Expanded(
                          child: TextField(
                            enabled: t2,
                            keyboardType: TextInputType.number,
                            controller: t2Controller,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(30.0),
                              ),
                              filled: true,
                              hintStyle: TextStyle(
                                color: Colors.grey[800],
                              ),
                              hintText: "",
                              label: Text("Unit Price"),
                              fillColor: Colors.white70,
                            ),
                            onChanged: (value) {
                              if ((t1Controller.text == "" || !t1) &&
                                  (t3Controller.text != "")) {
                                setState(() {
                                  t1 = false;
                                  t2 = true;
                                  t3 = true;
                                  t1Controller.text = value == ""
                                      ? ""
                                      : (num.parse(t3Controller.text) /
                                              num.parse(value))
                                          .toString();
                                });
                              }
                              if (t1Controller.text != "" &&
                                  (t3Controller.text == "" || !t3)) {
                                setState(() {
                                  t3 = false;
                                  t1 = true;
                                  t2 = true;
                                  t3Controller.text = value == ""
                                      ? ""
                                      : (num.parse(value) *
                                              num.parse(t1Controller.text))
                                          .toString();
                                });
                              }
                              if (t2Controller.text == "" &&
                                  t1Controller.text == "" &&
                                  t3Controller.text == "") {
                                setState(() {
                                  t2 = true;
                                  t1 = true;
                                  t3 = true;
                                });
                              }
                            },
                          ),
                        ),
                        Text(" = "),
                        Expanded(
                          child: TextField(
                            enabled: t3,
                            keyboardType: TextInputType.number,
                            controller: t3Controller,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(30.0),
                              ),
                              filled: true,
                              hintStyle: TextStyle(
                                color: Colors.grey[800],
                              ),
                              hintText: "",
                              label: Text("Total Price"),
                              fillColor: Colors.white70,
                            ),
                            onChanged: (value) {
                              if ((t1Controller.text == "" || !t1) &&
                                  (t2Controller.text != "")) {
                                setState(() {
                                  t1 = false;
                                  t3 = true;
                                  t2 = true;
                                  t1Controller.text = value == ""
                                      ? ""
                                      : (num.parse(value) /
                                              num.parse(t2Controller.text))
                                          .toString();
                                });
                              }
                              if (t1Controller.text != "" &&
                                  (t2Controller.text == "" || !t2)) {
                                setState(() {
                                  t2 = false;
                                  t1 = true;
                                  t3 = true;
                                  t2Controller.text = value == ""
                                      ? ""
                                      : (num.parse(value) /
                                              num.parse(t1Controller.text))
                                          .toString();
                                });
                              }
                              if (t2Controller.text == "" &&
                                  t1Controller.text == "" &&
                                  t3Controller.text == "") {
                                setState(() {
                                  t2 = true;
                                  t1 = true;
                                  t3 = true;
                                });
                              }
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  ElevatedButton(
                      onPressed: () {
                        setState(() {
                          t2 = true;
                          t1 = true;
                          t3 = true;
                          t2Controller.text == "";
                          t1Controller.text == "";
                          t3Controller.text == "";
                        });
                      },
                      child: Text("Reset"))
                ],
              ),
            ),
          ),
        );
      }
    }
    

    output screen