Skip to content

Instantly share code, notes, and snippets.

@rohan20
Created December 31, 2021 13:35
Show Gist options
  • Save rohan20/7c6925d06284d3172a84e5db8f505a3b to your computer and use it in GitHub Desktop.
Save rohan20/7c6925d06284d3172a84e5db8f505a3b to your computer and use it in GitHub Desktop.
Flutter close iOS number keyboard (has no "Done" button)
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: KeyboardVisibilityBuilder(
builder: (BuildContext context, bool isKeyboardVisible) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: isKeyboardVisible
? () {
FocusScope.of(context).unfocus();
print("Keyboard closed");
}
: null,
child: AbsorbPointer(
absorbing: isKeyboardVisible,
child: Scaffold(
appBar: AppBar(title: const Text("Close Keyboard Example")),
body: Center(
child: Column(
children: const [
SizedBox(height: 24),
_AnyTappableWidget(),
SizedBox(height: 24),
_DigitsOnlyTextField(),
],
),
),
),
),
);
},
),
);
}
}
class _AnyTappableWidget extends StatelessWidget {
const _AnyTappableWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => print("Text Tapped"),
child: const Text("A tappable widget"),
);
}
}
class _DigitsOnlyTextField extends StatelessWidget {
const _DigitsOnlyTextField({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
decoration: const InputDecoration(
hintText: "Digits only",
border: OutlineInputBorder(),
),
controller: TextEditingController(),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
),
);
}
}
@rohan20
Copy link
Author

rohan20 commented Dec 31, 2021

Since the iOS number keyboard doesn't have a done button to close the keyboard, this approach uses a combination of KeyboardVisibilityBuilder (from the flutter_keyboard_visibility package), GestureDetector and AbsorbPointer widgets to close the keyboard on tapping anywhere outside the keyboard; even if there are other tappable widgets on the screen.

[See the logs in the "Run" window of this video for more context]

close-keyboard-example.mov

@Isuru-Nanayakkara
Copy link

Thank you so much! 🙏🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment