【问题标题】:How to Change Button text depending on textfield?如何根据文本字段更改按钮文本?
【发布时间】:2021-10-29 15:35:13
【问题描述】:

enter image description here

在这里我想更改依赖于文本字段的按钮,例如当文本字段被填充时显示按钮 C,当单击 C 按钮时,将按钮名称 C 更改为 AC 并且还需要更改文本字段填充为空。

【问题讨论】:

  • 能把code-sn-p包括进去吗?

标签: flutter dart button text textfield


【解决方案1】:

查看此示例以演示您需要的输出

    import 'package:flutter/material.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Location',
          theme: ThemeData(
            primarySwatch: Colors.amber,
          ),
          home: const MyHomePage(title: 'Flutter Location Demo'),
        );
      }
    }

    class MyHomePage extends StatefulWidget {
      const MyHomePage({Key? key, this.title}) : super(key: key);
      final String? title;

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

    class _MyHomePageState extends State<MyHomePage> {
      final TextEditingController _controller = TextEditingController();
      String? buttonText;
      @override
      void initState() {
        _controller.addListener(_checkTextIsEmpty);
        super.initState();
      }

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title!),
          ),
          body: Center(
            child: Column(
              children: [
                TextField(
                  controller: _controller,
                  onChanged: (value) {},
                ),
                Text(buttonText ?? ''),
              ],
            ),
          ),
        );
      }

      void _checkTextIsEmpty() {
        final value = _controller.text.isEmpty ? "AC" : "C";
        setState(() {
          buttonText = value;
        });
      }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多