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

Time:01-01

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()

Feel free to leave a comment if you need more information.

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

CodePudding user response:

full example:

code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = TextEditingController();
  String _text = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Demo Home Page'),
      ),
      body: Container(
        padding: const EdgeInsets.all(16),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(_text),
              const SizedBox(height: 20),
              TextField(
                controller: _controller,
                onChanged: (value) {
                  setState(() {
                    _text = value;
                  });
                },
                decoration: const InputDecoration(
                  hintText: 'Enter text',
                ),
              ),

              // submit
              ElevatedButton(
                onPressed: _text.isEmpty
                    ? null
                    : () {
                        setState(() {
                          _text = _controller.text;
                        });
                      },
                child: const Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

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"))
      ],
    );
  }
}

CodePudding user response:

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

  • Related