I have main.dart
part 'home_page.dart';
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _judul = 'Private Chat';
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: MaterialApp(
title: _judul,
home: HomePage(), // Using separated file
),
);
}
}
And home_page.dart
part of 'main.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: TextField(),
);
}
}
FocusScope.of(context).unfocus() doesn’t work when I split widget from main.dart to another file (in this case home_page.dart) so the project will neat.
However It’s work when I directly put HomePage() return (Scaffold) to main.dart, (I say work because android keybord disappear when unfocused from textfield)
part 'home_page.dart';
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _judul = 'Private Chat';
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: MaterialApp(
title: _judul,
home: Scaffold(...), //Directly put textfield
),
);
}
}
I sus this is context mistake, I have no idea with context properties and method.
>Solution :
Put your GestureDetector under MaterialApp (swap them) and wrap it with Builder, like this:
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _judul = 'Private Chat';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _judul,
home: Builder(
builder: (context) {
return GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: HomePage(),
);
},
),
);
}
}
The reason this is working is because Builder gives you new context which is used in onTap function of your GestureDetector. This new context contains more specific details about position in the widget tree than the one you were previously using (which comes from the build method parameter).