Как остановить автоматическую фокусировку текстового поля при доступе к ящику в Flutter

#android #flutter #material-design #flutter-layout

Вопрос:

В чем проблема

После ввода чего-то в моем textField s в нижней синей части формы, а затем доступа к ящику каким-то образом фокусируется на последнем использованном 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 файл содержит только два обычных текстовых поля и их стили в виджете с отслеживанием состояния.

Комментарии:

1. Используйте, FocusManager.instance.primaryFocus.unfocus(); Вы можете обратиться к нижеприведенной теме для этого github.com/flutter/flutter/issues/54277

2. @Kashifa вы абсолютно правы, приятель, спасибо за помощь. хороший день

Ответ №1:

В 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 , вы абсолютно правы.

Следуйте этой теме для получения дополнительной информации.