How to stop Text Field from getting auto focused when accessing drawer in Flutter
534
In the BlogHome.dart
file
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(),
],
),
);
}
}
This is the correct solution @Kashifa
you are absolutely correct.
Follow this thread for more info.
Author by
Soumalya Bhattacharya
Currently learning and working on both front and back end with the vision to be a full stack dev.
Updated on December 29, 2022Comments
-
Soumalya Bhattacharya over 1 year
What is the problem
After entering something in my
textField
s in the lower blue part of the form and then accessing the drawer somehow focuses the last usedtextField
and activates the keyboard.Expected Behaviour
When the drawer menu is triggered, the
TextField
should not get focused and keyboard should not come up.Side Note
Till I don't enter any data in thetextField
drawer action works correctly without activating the keyboard.Code
In the
main.dart
file: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(), ); } }
In the
BlogHome.dart
fileimport '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
file contains just two normal text fields and their styles in a stateful widget.-
Kashifa about 3 yearsUse, FocusManager.instance.primaryFocus.unfocus(); You can refer the below thread for it github.com/flutter/flutter/issues/54277
-
Soumalya Bhattacharya about 3 years@Kashifa you are absolutely correct mate thanks for help. Good Day
-