Created
June 8, 2022 21:20
-
-
Save DaisukeNagata/0b9222c3ac5650a47d2d91c58ed86584 to your computer and use it in GitHub Desktop.
keyboard open check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const CheckKeyBoard()); | |
} | |
class CheckKeyBoard extends StatelessWidget { | |
const CheckKeyBoard({Key? key}) : super(key: key); | |
// This widget is the root of your application. | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({Key? key, required this.title}) : super(key: key); | |
final String title; | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
final key = const KeyboardCheck(); | |
var focusNode = FocusNode(); | |
@override | |
void initState() { | |
super.initState(); | |
focusNode.addListener(() { | |
if (!focusNode.hasFocus) key.close(); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
if (focusNode.hasFocus) { | |
key.check(MediaQuery.of(context).viewInsets.bottom); | |
} | |
return Scaffold( | |
appBar: AppBar( | |
title: key, | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
TextField( | |
focusNode: focusNode, | |
onTap: () => FocusScope.of(context).requestFocus(focusNode), | |
), | |
], | |
), | |
), | |
); | |
} | |
} | |
class KeyboardCheck extends StatelessWidget { | |
const KeyboardCheck({Key? key}) : super(key: key); | |
static var streamController = StreamController<String?>(); | |
void close() { | |
streamController.sink.add(null); | |
} | |
void check(double keyboardHeight) { | |
var counter = 0; | |
while (counter < keyboardHeight) { | |
counter += 1; | |
if (counter == keyboardHeight) { | |
streamController.sink.add('Keyboard Open'); | |
} | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return StreamBuilder( | |
stream: streamController.stream, | |
builder: ( | |
BuildContext context, | |
AsyncSnapshot<String?> snapShot, | |
) { | |
if (snapShot.data?.isNotEmpty ?? false) { | |
return Text( | |
snapShot.data ?? '', | |
style: const TextStyle(color: Colors.black), | |
); | |
} else { | |
return const Text( | |
'Keyboard Close', | |
style: TextStyle(color: Colors.white), | |
); | |
} | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2022-06-09.6.15.37.mov