Skip to content

Instantly share code, notes, and snippets.

@dkwingsmt
Created July 21, 2020 23:01
Show Gist options
  • Select an option

  • Save dkwingsmt/ac5eb9ae22c3b2d5c7190e2bfc525ede to your computer and use it in GitHub Desktop.

Select an option

Save dkwingsmt/ac5eb9ae22c3b2d5c7190e2bfc525ede to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
List<RawKeyEvent> events = <RawKeyEvent>[];
bool _handleKey(FocusNode node, RawKeyEvent event) {
setState(() {
if (events.length > 4)
events.removeRange(0, 1);
events.add(event);
});
return true;
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
...events.expand((RawKeyEvent event) =>
<Widget>[
Text('${event?.runtimeType}'),
Text('${event?.logicalKey}'),
Text('${event?.physicalKey}'),
],
),
Focus(
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: FocusableArea(
onKey: _handleKey,
),
),
),
),
],
)
);
}
}
class FocusableArea extends StatefulWidget {
FocusableArea({this.onKey});
final FocusOnKeyCallback onKey;
@override
State<StatefulWidget> createState() => _FocusableAreaState();
}
class _FocusableAreaState extends State<FocusableArea> {
final FocusNode node = FocusNode();
bool _isFocused = false;
@override
Widget build(BuildContext context) {
return Focus(
onKey: widget.onKey,
onFocusChange: (bool value) {
setState(() {
_isFocused = value;
});
},
focusNode: node,
child: ColoredBox(
color: _isFocused ? Colors.blue : Colors.grey,
child: GestureDetector(
onTap: () {
if (_isFocused)
node.unfocus();
else
node.requestFocus();
},
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment