Skip to content

Instantly share code, notes, and snippets.

@eliezedeck
Last active December 16, 2020 18:04
Show Gist options
  • Save eliezedeck/d5dd208bf9bfcda49d4974df8baa3537 to your computer and use it in GitHub Desktop.
Save eliezedeck/d5dd208bf9bfcda49d4974df8baa3537 to your computer and use it in GitHub Desktop.
Detect `TextField` focus/unfocus (focus and blur in HTML terminology)
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// Data will be available here
final _inputController = TextEditingController();
// Focus will be manipulated thru this
final _inputFocus = FocusNode();
// This is what we display and mutate when there is update in focus
bool focused = false;
@override
void initState() {
super.initState();
_inputFocus.addListener(() {
// We'll be notified here when there is a change in focus
print('focus change: ${_inputFocus.hasFocus}');
setState(() {
focused = _inputFocus.hasFocus;
});
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
// This allows losing the focus when the user taps on anything else
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
currentFocus.unfocus();
}
},
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Focus:',
),
Text(
'$focused',
style: Theme.of(context).textTheme.headline4,
),
Container(height: 16.0),
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
controller: _inputController,
focusNode: _inputFocus,
),
),
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment