From ccd38eac2ab09627db60670a850178a45fbc4bb7 Mon Sep 17 00:00:00 2001 From: h7x4abk3g Date: Wed, 22 Jul 2020 15:22:21 +0200 Subject: [PATCH] Separate text field logic --- lib/screens/kanji_search.dart | 79 ++++++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 19 deletions(-) diff --git a/lib/screens/kanji_search.dart b/lib/screens/kanji_search.dart index 557d071..250b128 100644 --- a/lib/screens/kanji_search.dart +++ b/lib/screens/kanji_search.dart @@ -53,25 +53,7 @@ class KanjiViewBar extends StatelessWidget { ), Expanded( child: Container( - child: TextField( - onChanged: (text) => BlocProvider.of(context) - .add(GetKanjiSuggestions(text)), - onSubmitted: (text) => - BlocProvider.of(context).add(GetKanji(text)), - decoration: new InputDecoration( - prefixIcon: Icon(Icons.search), - hintText: 'Search for kanji', - fillColor: Colors.white, - filled: true, - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(100.0), - ), - contentPadding: EdgeInsets.symmetric(vertical: 10.0), - isDense: false), - style: TextStyle( - fontSize: 14.0, - ), - ), + child: _KanjiTextField(), ), ), IconButton( @@ -87,3 +69,62 @@ class KanjiViewBar extends StatelessWidget { ); } } + +class _KanjiTextField extends StatefulWidget { + @override + _KanjiTextFieldState createState() => new _KanjiTextFieldState(); +} + +class _KanjiTextFieldState extends State<_KanjiTextField> { + FocusNode _focus = new FocusNode(); + TextEditingController _textController = new TextEditingController(); + + @override + void initState() { + super.initState(); + _focus.addListener(_onFocusChange); + } + + void _onFocusChange() { + debugPrint('TextField Focus Changed: ${_focus.hasFocus.toString()}'); + if (_focus.hasFocus) _getKanjiSuggestions(_textController.text); + else FocusScope.of(context).unfocus(); + } + + void _getKanjiSuggestions(String text) => + BlocProvider.of(context).add(GetKanjiSuggestions(text)); + + void _clearText() { + _textController.text = ''; + _getKanjiSuggestions(_textController.text); + } + + @override + Widget build(BuildContext context) { + return TextField( + focusNode: _focus, + controller: _textController, + onChanged: (text) => _getKanjiSuggestions(text), + onSubmitted: (text) => + BlocProvider.of(context).add(GetKanji(text)), + decoration: new InputDecoration( + prefixIcon: Icon(Icons.search), + hintText: 'Search for kanji', + fillColor: Colors.white, + filled: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(100.0), + ), + contentPadding: EdgeInsets.symmetric(vertical: 10.0), + isDense: false, + suffixIcon: IconButton( + icon: Icon(Icons.clear), + onPressed: () => _clearText(), + ) + ), + style: TextStyle( + fontSize: 14.0, + ), + ); + } +}