首页 > 解决方案 > 在 Flutter 中访问抽屉时如何阻止文本字段自动聚焦

问题描述

问题是什么

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

在此处输入图像描述

预期行为

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

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

代码

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文件仅包含两个普通文本字段及其在有状态小部件中的样式。

标签: androidfluttermaterial-designflutter-layout

解决方案


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您绝对正确的正确解决方案。

关注此线程以获取更多信息。


推荐阅读