Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the text in textfield disappears when I press the back button or remove my keyboard

I have problem with this code:

This Login Page:

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

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

class _LoginPageState extends State<LoginPage> {
  @override
  Widget build(BuildContext context) {
    final TextEditingController _emailController = TextEditingController();
    final TextEditingController _passwordController = TextEditingController();
    double h = MediaQuery.of(context).size.height;

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            const AuthHeader(
              firstText: 'Login', 
              secText: 'Sign into your account',
              flip: false,
              beginC: Alignment.topRight,
              endC: Alignment.bottomLeft,
              caAlignment: CrossAxisAlignment.start,
            ),
            SizedBox(height: h * 0.05),
            TextFieldAuth(
              controller: _emailController,
              hintText: 'E-Mail',
              icon: Icons.mail,
            ),
            SizedBox(height: h * 0.03),
            TextFieldAuth(
              controller: _passwordController,
              hintText: 'Password',
              icon: Icons.password,
            ),
            SizedBox(height: h * 0.06),
            const ButtonAuth(
              text: 'Sign In',
            ),
            SizedBox(height: h * 0.07),
            AuthRichText(
              firstText: 'Don\'t have account? ',
              secText: 'Create',
              recognizer: TapGestureRecognizer()..onTap = () {
                Get.toNamed('/signup');
              }
            ),
            SizedBox(height: h * 0.03),
            const DividerAuth(),
            SizedBox(height: h * 0.02),
            const GroupAuthButton(),
          ],
        ),
      ),
    );
  }
}

This SignUp page:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

class _SignUpPageState extends State<SignUpPage> {
  @override
  Widget build(BuildContext context) {
    final TextEditingController _emailController = TextEditingController();
    final TextEditingController _passwordController = TextEditingController();
    double h = MediaQuery.of(context).size.height;
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            const AuthHeader(
              firstText: 'SignUp',
              secText: 'Create your account',
              flip: true,
              beginC: Alignment.bottomLeft,
              endC: Alignment.topRight,
              caAlignment: CrossAxisAlignment.end,
            ),
            SizedBox(height: h * 0.05),
            TextFieldAuth(
              controller: _emailController,
              hintText: 'E-Mail',
              icon: Icons.mail,
            ),
            SizedBox(height: h * 0.03),
            TextFieldAuth(
              controller: _passwordController,
              hintText: 'Password',
              icon: Icons.password,
            ),
            SizedBox(height: h * 0.06),
            const ButtonAuth(
              text: 'Sign Up',
            ),
            SizedBox(height: h * 0.07),
 

       AuthRichText(
          firstText: 'Have account? ',
          secText: 'Sign In',
          recognizer: TapGestureRecognizer()..onTap = () {
            Get.back();
          }
        ),
        SizedBox(height: h * 0.03),
        const DividerAuth(),
        SizedBox(height: h * 0.02),
        const GroupAuthButton(),
      ],
    ),
  ),
);

}
}

and this the textfield:

import 'package:flutter/material.dart';

class TextFieldAuth extends StatelessWidget {
  const TextFieldAuth({
    Key? key,
    this.hintText, this.icon, this.controller,
  }) : super(key: key);

  final String? hintText;
  final IconData? icon;
  final TextEditingController? controller;

  @override
  Widget build(BuildContext context) {
    double w = MediaQuery.of(context).size.width;
    return Container(
      width: w * 0.90,
      decoration: const BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        boxShadow: [
          BoxShadow(
            blurRadius: 10,
            spreadRadius : 2,
            offset: Offset(0, 8),
            color: Colors.grey
          )
        ]
      ),
      child: TextField(
        controller: controller,
        decoration: InputDecoration(
          hintText: hintText,
          fillColor: Colors.white,
          prefixIcon: Icon(icon, color: Colors.redAccent,),
          filled: true,
          border: const OutlineInputBorder(
            borderSide: BorderSide.none,
            borderRadius: BorderRadius.all(Radius.circular(20))
          )
        ),
      ),
    );
  }
}

i don’t know why this can happen suddenly even though previously this code was running fine.when I enter text in the TextField, the text always disappears when I close the keyboard or I press the back button. can this problem be solved?

>Solution :

You shouldn’t create TextEditingControllers inside build method. Every time the widget rebuilds (for example, after calling setState() or simply hot reloading), your controllers will be recreated, so values stored by them would get lost. You should instantiate your controllers directly in state, like this:

  class _SignUpPageState extends State<SignUpPage> {
    final TextEditingController _emailController = TextEditingController();
    final TextEditingController _passwordController = TextEditingController();

    @override
    Widget build(BuildContext context) {
     ...

Also, don’t forget to dispose your controllers when you no longer need them. Put this function in your state class:

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

For more information, refer to:

https://api.flutter.dev/flutter/widgets/TextEditingController-class.html

https://flutter.dev/docs/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading