如何在Flutter中从TextFormField更新变量?

问题描述 投票:0回答:2

我有TextFormField,它具有自己的控制器。我还有一个禁用的按钮,想要在TextFormField中进行任何输入后启用。问题是我设法仅在关闭键盘时才启用按钮。例如,如果我在会话中输入单词,除非关闭键盘,否则它将不会启用按钮。我想在第一个字符后启用按钮。

这是代码:

final TextEditingController passwordController = new TextEditingController();

TextFormField(
  keyboardType: TextInputType.visiblePassword,
  controller: passwordController,
),

RaisedButton(
  onPressed: (passwordController.text== "") ? null : () {
    setState(() {
      _isLoading = true;
    });
    signIn(email, passwordController.text);
  },
),
flutter
2个回答
0
投票

这是您要寻找的吗?

final TextEditingController _controller = TextEditingController();
bool _isLoading = true;

@override
void initState() {
  super.initState();

  _controller.addListener(() { // you need to add listener like this
    setState(() {
      if (_controller.text.length > 0)
        _isLoading = false;
      else
        _isLoading = true;
    });
  });
}

Widget build(context) {
  return Scaffold(
    body: Column(
      children: <Widget>[
        SizedBox(height: 50),
        TextFormField(controller: _controller),
        RaisedButton(
          onPressed: _isLoading ? null : () => setState(() => _isLoading = true),
        ),
      ],
    ),
  );
}

0
投票

此方法有效:

var password = '';

TextFormField(
  keyboardType: TextInputType.visiblePassword,
  controller: passwordController,
  onChanged: (value){
    setState(() {
      password = value;
    });
  },
),

RaisedButton(
  onPressed: (password == "") ? null : () {
    setState(() {
      _isLoading = true;
    });
    signIn(email, password);
  },
),

推荐问答