简体   繁体   中英

How do I dismiss the keyboard in TextFormfield flutter 2.0.1

Hey how do I dismiss the keyboard here? I want the keyboard to dismiss when tapped outside the area.

  Widget build(BuildContext context) {
return Padding(
  padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
  child: TextFormField(
    keyboardType: TextInputType.number,
    maxLength: 10,
    controller: widget._phoneController,
    onTap: () => FocusScope.of(context).unfocus(),
    inputFormatters: [
      //input type
      FilteringTextInputFormatter.allow(
        RegExp(r'[0-9]'),
      ),
    ],
    //how the text box is decorated
    decoration: buildInputDecoration(
        Icons.phone, 'Enter your 10 digit phone number'),
  ),
);
}

You can wrap your parent widget that spans the entire screen with a widget that can detect clicks. In the onClick ,

FocusScope.of(context).unfocus()

FocusScope.of(context) gets the currently focused node and .unfocus() unfocuses it.

This works because when the TextFormField is clicked, it consumes the click. So the parent widget's onClick is not triggered. So no unfocussing happens.

When we click outside, the parent widget consumes the click event, because none of its children consume it. Thus, the parent's onClick is triggered.

Below is an example. You can see a demo on DartPad .
(Although, it's best to run it on a mobile device so you can see the on screen keyboard.)

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hide keyboard in TextFormField when touched outside'),
      ),
      body: GestureDetector(
        onTap: () {
          print('Clicked outside');
          FocusScope.of(context).unfocus();
        },
        child: Container(
          color: Colors.white,
          child: Form(
            child: Column(
              children: [
                TextFormField(
                  onTap: () => print('Clicked TextFormField'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Worked for me:)

  TextField(
        onSubmitted: (value) async {
          FocusScope.of(context).unfocus();
        },
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM