如何在Flutter中连续获取TextField的文本是否为空?

bmvo0sr5  于 2023-01-02  发布在  Flutter
关注(0)|答案(3)|浏览(175)

我有一个TextField。我希望它的文本不为空。(所以我想知道文本是否为空)
我试过使用下面的代码,但它不工作:

controller.text.trim().isEmpty()

我的代码:
x一个一个一个一个x一个一个二个x
如何在Flutter中连续获得TextField的文本是否为空?我将感谢任何帮助。提前感谢!

q43xntqr

q43xntqr1#

完整示例:

代码:

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

jchrr9hc2#

使用ValueListenableBuilder无需任何临时变量即可完成

经过研究发现

  1. controller.text本身不是listenable
  2. TextEditingController扩展了ValueNotifier<TextEditingValue>,即您可以使用材质包中的ValueListenableBuilder来侦听文本更改。
    代码:
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'),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

无文本:

文本:

hsvhsicv

hsvhsicv3#

您可以将侦听器添加到TextEditingController并调用setState来更新UI。

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

您将使用controller.text.trim().isEmpty()的位置将显示更新后的状态。
示例

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

相关问题