启用键盘后如何启用或禁用按钮?

时间:2019-07-02 02:01:19

标签: flutter dart flutter-layout

如何在验证TextFormField的过程中启用键盘时启用或禁用按钮?

class WordsFormPageState extends State<WordsFormPage> {
  var tps = new StringProcessor();
  var _isButtonDisabled = false;
.....
  @override
  Widget build(BuildContext context) {
   final editor = TextFormField(
      decoration: InputDecoration(labelText: 'Your essay'),
      keyboardType: TextInputType.multiline,
      autovalidate: true,
      minLines: 3,
      maxLines: 20,
      validator: (value) {
        if (value.isEmpty) {
          return 'Enter some text';
        }
        if (tps.getWordCount(value) == 100) {
          _isButtonDisabled = false;
        } else {
          _isButtonDisabled = true;
          return "${tps.getWordCount(value)}/100";
        }
        print(_isButtonDisabled);
        return null;
      },
    );
   final form = ListView(
      children: <Widget>[
        ExerciceCardSmall(
          exercice: widget.exercice,
        ),
        Card(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: editor,
          ),
        ),
      ],
    );    
   return Scaffold(
      resizeToAvoidBottomPadding: true,
      appBar: AppBar(
        title: Text(widget.exercice.title),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.save),
            onPressed: _isButtonDisabled ? null : () {},
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: form,
      ),
    );
  }
}

我期望当单词数= 100时,IconButton会被禁用,但是直到隐藏键盘后,该按钮才会被禁用或启用。

编辑: 在build methode中使用setState会引发异常,解决方案是用addPostFrameCallback包裹

if (tps.getWordCount(value) == 100) {
       SchedulerBinding.instance
                       .addPostFrameCallback((_) => setState(() {
                                          _isButtonDisabled = false;
                                        }));
} else {
       SchedulerBinding.instance
                       .addPostFrameCallback((_) => setState(() {
                                          _isButtonDisabled = true;
                                        }));
       return "${tps.getWordCount(value)}/100";
}

1 个答案:

答案 0 :(得分:0)

您应该在验证器函数中调用setState,让Flutter知道它已更改页面的状态。

例如:

if (tps.getWordCount(value) == 100) {
  setState(() {
    _isButtonDisabled = false;
  });
} else {
  setState(() {
    _isButtonDisabled = true;
  });
  return "${tps.getWordCount(value)}/100";
}