Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to continuously get whether the TextField's text is empty in Flutter?

Tags:

flutter

dart

I have a TextField. I want its text not to be empty. (so I want to know if the text is empty)

I have tried using the following code, but it doesn't work:

controller.text.trim().isEmpty()

My code:

TextFormField(
  controller: controller,
),

controller.text.trim().isEmpty()

How to continuously get whether the TextField's text is empty in Flutter? I would appreciate any help. Thank you in advance!

like image 829
My Car Avatar asked Oct 23 '25 14:10

My Car


2 Answers

It can be done without any temporary variable using ValueListenableBuilder

After some research figured out

  1. controller.text by itself is not listenable
  2. TextEditingController extends ValueNotifier<TextEditingValue> i.e you can use ValueListenableBuilder from material package to listen to text changes.

Code:

class _MyWidgetState extends State<MyWidget> {
  late TextEditingController textEditingController;
  @override
  void initState() {
    textEditingController = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: [
            TextField(
              controller: textEditingController,
            ),
            ValueListenableBuilder<TextEditingValue>(
              valueListenable: textEditingController,
              builder: (context, value, child) {
                return ElevatedButton(
                  onPressed: value.text.isNotEmpty ? () {} : null,
                  child: const Text('I am disabled when text is empty'),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

Without text:

enter image description here

With text:

enter image description here

like image 172
krishnaacharyaa Avatar answered Oct 26 '25 05:10

krishnaacharyaa


You can add listener to your TextEditingController and call setState to update the UI.

late TextEditingController controller  = TextEditingController()..addListener(() {
   
   setState((){}); // to update the ui
  });

The place you will use controller.text.trim().isEmpty() will show the updated state.

Example

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

  @override
  State<Test> createState() => _TestState();
}

class _TestState extends State<Test> {
  late TextEditingController controller = TextEditingController()
    ..addListener(() {
      setState(() {}); // to update the ui
    });
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(
          controller: controller,
        ),
        ElevatedButton(
            onPressed: controller.text.trim().isEmpty ? null : () {},
            child: Text("Button"))
      ],
    );
  }
}
like image 38
Yeasin Sheikh Avatar answered Oct 26 '25 05:10

Yeasin Sheikh