2

I am passing some user information from the first screen to the second screen and on the second screen, I am trying to edit that information inside a TextField. My code for the second screen is as follows.

class EditProfile extends StatefulWidget {
  String profName;
  String profOcc;
  EditProfile({Key? key, required this.profName, required this.profOcc,}): super(key: key);

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

class _EditProfileState extends State<EditProfile> {

  @override
  Widget build(BuildContext context) {
    var nameController = TextEditingController()..text = widget.profName;
    var occController = TextEditingController()..text = widget.profOcc;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        elevation: 1,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Color(0xFF6f6bdb),
          ),
          onPressed: (){
            Navigator.pop(context);
          },
          ),
    ),
    body: Container(
      padding: EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 0.0),
      child: GestureDetector(
        onTap: () {FocusScope.of(context).unfocus();},
        child: ListView(
          children: [
            Text(
              "Edit Profile",
            ),
            SizedBox(height: 20.0),
            createInputField("NAME", nameController),
            createInputField("OCCUPATION", occController),
            SizedBox(height: 25.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ElevatedButton(
                  onPressed: () async {
                    //// Update the values when pressed
                  },
                  style: ElevatedButton.styleFrom(
                    primary: Color(0xFF6f6bdb), // background
                    padding: EdgeInsets.symmetric(horizontal: 50),
                  ),
                  child: Text(
                    "UPDATE",
                  )
                ),
              ],
            )
          ],
        ),
      ),
    ),
    );
  }

  TextField createInputField(String labelText, TextEditingController controller) {
    return TextField(
            controller: controller,
            decoration: InputDecoration(
              isDense: true,
              labelText: "$labelText:",
              floatingLabelBehavior: FloatingLabelBehavior.always,
              hintStyle: TextStyle(
                fontSize: 16, fontWeight: FontWeight.w700,
                color: Colors.black,
              )
            ),
          );
  }

My problem is that since I am initialising the text editing controllers inside the Widget, when I edit the values in a TextField and then defocus the field the value inside the TextField reverts back to the initial value. My question is, is there a way to initialise the text editing controllers outside the Widget and still set the initial values using the values I am getting from the first screen? The widget.profName does not work outside the Widget. Any help on this is much appreciated.

AnuIzu
  • 27
  • 1
  • 5

1 Answers1

8

You can create a TextEditingController outside build method, by setting its value in the init field. Like so,

class SecondPage extends StatefulWidget {
  final String myString;
  const SecondPage({Key? key, required this.myString}) : super(key: key);

  @override
  State<SecondPage> createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {


late final TextEditingController controller;
  @override
  void initState() {
    super.initState();
    controller = TextEditingController(text: widget.myString);
  }
  
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

Another way you can also do is assigned the value outside the init field if you assign late to your variable

class SecondPage extends StatefulWidget {
  final String myString;
  const SecondPage({Key? key, required this.myString}) : super(key: key);

  @override
  State<SecondPage> createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> {


late final TextEditingController controller = TextEditingController(text: widget.myString);

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

Remember to dispose the textController once you stopped using it. linked: https://api.flutter.dev/flutter/widgets/TextEditingController-class.html

IcyHerrscher
  • 391
  • 3
  • 9
  • Great. That solved the problem I had. Much appreciate the help. Thanks! – AnuIzu Oct 01 '21 at 16:14
  • Glad to help, no problem. – IcyHerrscher Oct 01 '21 at 16:41
  • I've seen similar examples that also include an overridden `dispose` method to dispose of the TextEditingController. How important is it (if at all) to do this? – Sam Hiatt Feb 01 '23 at 04:31
  • According to the document https://api.flutter.dev/flutter/widgets/TextEditingController-class.html, it would likely cause a memory leak if we doesn't dispose of it. I will update my code. I was only aware that we have to dispose of it if we have any listener attach to it. – IcyHerrscher Feb 04 '23 at 02:54