在 Flutter 中访问抽屉时如何阻止文本字段自动聚焦

How to stop Text Field from getting auto focused when accessing drawer in Flutter

What is the problem

在我的 textField 表单蓝色下方部分输入内容后,访问抽屉以某种方式聚焦最后使用的 textField 并激活键盘。

Expected Behaviour

当抽屉菜单被触发时,TextField 不应该获得焦点并且键盘不应该出现。

旁注
直到我不在 textField 中输入任何数据,抽屉操作在不激活键盘的情况下工作正常。

Code

main.dart 文件中:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       //NavDrawer() is the custom Widget that renders the Drawer
      drawer: NavDrawer(),
      appBar: AppBar(
        ...<Normal Appbar Stuff>
      ),
        // BlogHome() is the custom Widget rendering the body
      body: BlogHome(),
    );
  }
}

BlogHome.dart文件中

import 'package:flutter/material.dart';
import 'form.dart';

class BlogHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          GestureDetector(
            onTap: () {
              FocusScope.of(context).unfocus();
              new TextEditingController().clear();
            },
            child: Column(
              children: <Widget>[
                ...<Other Widgets>
              ],
            ),
          ),
           // This custom widget renders the blue colored form in the bottom
          FormData(),
        ],
      ),
    );
  }
}

FormData.dart 文件仅包含两个普通文本字段及其在有状态小部件中的样式。

BlogHome.dart文件中

import 'package:flutter/material.dart';
import 'form.dart';

class BlogHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          GestureDetector(
            onTap: () {
// This line is unfocusing the current context that is calling unfocus upon itself
//But what it needs to do is call unfocus upon the primary focus
//So, commenting this line

              //FocusScope.of(context).unfocus();

// This is the correct approach of calling unfocus on primary focus
  FocusManager.instance.primaryFocus.unfocus();
              new TextEditingController().clear();
            },
            child: Column(
              children: <Widget>[
                ...<Other Widgets>
              ],
            ),
          ),
           // This custom widget renders the blue colored form in the bottom
          FormData(),
        ],
      ),
    );
  }
}

这是正确的解决方案@Kashifa你完全正确。

Follow this thread for more info.