Home > Software engineering >  (Flutter and Dart) clicking a button or a radio button clears the textbox
(Flutter and Dart) clicking a button or a radio button clears the textbox

Time:11-27

I am writing a flutter program that gets user details. Unfortunately even though my TextEditing Controllers are set up correctly. Everytime I click a button or a radio button, textboxes are cleared instantly even though I did not have any code that clears them

Here is the code


import 'package:flutter/material.dart';
import 'NavDrawer.dart';

class proFile extends StatelessWidget {
  static const String routeName = '/profile';

  const proFile({super.key});

  @override
  build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Profile"),
        ),
        drawer: const NavDrawer(),
        body: ProfileScreen());
  }
}

class ProfileScreen extends StatefulWidget {
  const ProfileScreen({super.key});

  @override
  _ProfileScreenState createState() {
    return _ProfileScreenState();
  }
}

enum Gender { male, female }
String getGender="";
class _ProfileScreenState extends State<ProfileScreen> {
  @override
  Gender? _gender = Gender.male;

  Widget build(BuildContext context1) {
    TextEditingController getUsername = TextEditingController();
    TextEditingController getFName = TextEditingController();
    TextEditingController getLName = TextEditingController();
    TextEditingController getPass = TextEditingController();
    TextEditingController getCPass = TextEditingController();
    TextEditingController getEmail = TextEditingController();
    TextEditingController var5 = TextEditingController();


    return SingleChildScrollView(

      child: Column(

        children: <Widget>[
          Row(
            children: <Widget>[
              Container(
                margin: EdgeInsets.all(20),
                child: Text("Enter Your Profile",
                    style: TextStyle(fontSize: 40, color: Colors.black)),
              ),
            ],
          ),
          //row2
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                width: 500,
                margin: EdgeInsets.all(10),
                child: TextField(
                    keyboardType: TextInputType.text,
                    controller: getUsername,
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(
                            borderSide:
                                const BorderSide(color: Colors.lightGreen)),
                        labelText: "Enter Your UserName")),
              )
            ],
          ),
          //row3
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                width: 500,
                margin: EdgeInsets.all(10),
                child: TextField(

                    controller: getFName,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(
                            borderSide:
                                const BorderSide(color: Colors.lightGreen)),
                        labelText: "Enter Your First Name")),
              )
            ],
          ),
          //row4
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                width: 500,
                margin: EdgeInsets.all(10),
                child: TextField(

                    controller: getLName,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(
                            borderSide:
                                const BorderSide(color: Colors.lightGreen)),
                        labelText: "Enter Your Last Name")),
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                width: 500,
                margin: EdgeInsets.all(10),
                child: TextField(

                    controller: getPass,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(
                            borderSide:
                                const BorderSide(color: Colors.lightGreen)),
                        labelText: "Enter Your Password")),
              )
            ],
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                width: 500,
                margin: EdgeInsets.all(10),
                child: TextField(

                    controller: getCPass,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(),
                        labelText: "Confirm Your Password")),
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                width: 500,
                margin: EdgeInsets.all(10),
                child: TextField(

                    controller: getEmail,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: const OutlineInputBorder(),
                        labelText: "Enter Your Email")),
              )
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 50,
                width: 400,
                child:ListTile(
                  title: const Text('Male'),
                  leading: Radio(
                    value: Gender.male,
                    groupValue: _gender,
                    onChanged: (Gender? value) {
                      setState(() {
                        _gender = value;
                      });
                    },
                  ),
                ),
              ),
              Container(
                height: 50,
                width: 400,
                child:ListTile(
                  title: const Text('Female'),
                  leading: Radio(
                    value: Gender.female,
                    groupValue: _gender,
                    onChanged: (Gender? value) {
                      setState(() {
                        _gender = value;

                      });
                    },
                  ),
                ),
              )

            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                height: 100,
                width: 500,

                margin: EdgeInsets.all(1),
                child: TextField(
                    maxLines: 8,

                    controller: var5,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        border: const UnderlineInputBorder(borderSide:
                        const BorderSide(color: Colors.lightGreen)),
                        labelText: "")),
              )
            ],
          ),
          Row(
              //button
              children: <Widget>[
                const SizedBox(height: 55.0, width: 20.0),

                SizedBox(

                  width: 250.0,
                  height: 70,
                  child: ElevatedButton(
                    child: const Text("Submit!"),
                    style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green,

                        padding: EdgeInsets.all(20),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20))),
                    onPressed: () {
                      setState(() {
                        String name = getUsername.text;
                        String fname = getFName.text;
                        String lname = getLName.text;
                        String pass = getPass.text;
                        String cpass = getCPass.text;
                        String email = getEmail.text;

                        var5.text="Inputted Result:\nName=$name\nFirst Name=$fname\nLast Name=$lname\nEmail=$email";
                      });
                    },
                  ),
                ),
              ]),


        ],
      ),
    );
  }
}

I tried clearing the radio button to see if it is the root of the issue but it still happens on the button

CodePudding user response:

This is happening because you are calling setState().

Every time you call setState() you ask flutter to check for changes and rebuild the UI (widget tree). So in your case, you have setState() every time you change the radio button for example which is why the UI is rebuilt and fields are clearing. Think of what happens to a form if you refresh the browser and don't save it anywhere. If you want to save _gender = value on radio change you can do that without a setState().

Your submit button should store and validate everything in your fields and then possibly call setState() based on what you want to do after.

I would highly recommend using Form & FormField for what you are trying to accomplish as you can maintain states more efficiently in that way.

Also have a look here

CodePudding user response:

Remove setState(){} from your button onPressed(){} and do something like this

var5.text ="Inputted Result:\nName=${getUsername.text}\nFirst Name=${getFName.text}\nLast Name=${getLName.text}\nEmail=${getEmail.text}";
  • Related