在输入Flutter上输入时禁用按钮

时间:2020-01-09 08:21:28

标签: flutter

我要在输入时禁用按钮。 但是我下面编写的代码不起作用,因为仅当我用键盘“确认”输入时,按钮才被禁用,但是我想在输入时键入输入以禁用输入

 TextEditingController myController = TextEditingController();
 bool isValid = false;
 @override
 Widget build(BuildContext context) {
   Column( 
      children: <Widget>[
         TextField(
            controller: myController,
            onChanged: (value){
               setState(() {
                  isValid = (value.isEmpty || double.tryParse(value) == null) ? false : true;
               });
            },
            decoration: InputDecoration(
               border: InputBorder.none,
               hintText: 'Enter a search term'
            ),
       ),
       RaisedButton(
          disabledColor: Colors.grey,
          child: Text("${AppLocalizations.of(context).translate("test")}"),
          onPressed: isValid ? () { print("test") }:null,
      ),
    ],
  )
}

2 个答案:

答案 0 :(得分:1)

使用FocusNode

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DemoPage(),
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primaryColor: Colors.white),
    );
  }
}

class DemoPage extends StatefulWidget {
  @override
  _DemoPageState createState() => _DemoPageState();
}

class _DemoPageState extends State<DemoPage> {
  TextEditingController textField1Ctrl;
  TextEditingController textField2Ctrl;
  FocusNode focusNode1;
  FocusNode focusNode2;

  @override
  void initState() {
    textField1Ctrl = TextEditingController();
    textField2Ctrl = TextEditingController();
    focusNode1 = FocusNode()..addListener(_rebuildOnFocusChange);
    focusNode2 = FocusNode()..addListener(_rebuildOnFocusChange);
    super.initState();
  }

  void _rebuildOnFocusChange() => setState(() {});

  void _onButton1Pressed() {}

  void _onButton2Pressed() {}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text("Disable Button When Text Field has focus"),
            Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: textField1Ctrl,
                    focusNode: focusNode1,
                  ),
                ),
                RaisedButton(
                  child: Text("Button 1"),
                  onPressed: focusNode1.hasFocus ? null : _onButton1Pressed,
                )
              ],
            ),
            const SizedBox(height: 40.0),
            Text("Disable Button When TextField is Empty or has focus"),
            Row(
              children: <Widget>[
                Expanded(
                  child: TextField(
                    controller: textField2Ctrl,
                    focusNode: focusNode2,
                  ),
                ),
                RaisedButton(
                  child: Text("Button 2"),
                  onPressed: focusNode2.hasFocus || textField2Ctrl.text.isEmpty
                      ? null
                      : _onButton2Pressed,
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

演示DartPad

答案 1 :(得分:0)

您也可以使用myController.addListener()

要检查结果,只需将以下代码复制并粘贴到DartPad

TextField中输入数字后,该按钮将启用

示例代码

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController myController = TextEditingController();
  bool isValid = false;

  @override
  void dispose() {
    // Clean up your controller when the Widget is disposed
    myController.dispose();
    super.dispose();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    myController.text = '';
    myController.addListener((){
      print("Get Value: ${myController.text}");
      setState(() {
        isValid = (myController.text.isEmpty || double.tryParse(myController.text) == null)
            ? false
            : true;
      });
    });

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          TextField(
            controller: myController,
            onChanged: (value) {
              setState(() {

              });
            },
            decoration: InputDecoration(
                border: InputBorder.none, hintText: 'Enter a search term'),
          ),
          RaisedButton(
            disabledColor: Colors.grey,
            child: Text("Click Me"),
            onPressed: isValid
                ? () {
                    print("test");
                  }
                : null,
          ),
        ],
      ),
    );
  }


}