Separate text field logic

This commit is contained in:
Oystein Kristoffer Tveit 2020-07-22 15:22:21 +02:00
parent 689983b848
commit ccd38eac2a
1 changed files with 60 additions and 19 deletions

View File

@ -53,25 +53,7 @@ class KanjiViewBar extends StatelessWidget {
),
Expanded(
child: Container(
child: TextField(
onChanged: (text) => BlocProvider.of<KanjiBloc>(context)
.add(GetKanjiSuggestions(text)),
onSubmitted: (text) =>
BlocProvider.of<KanjiBloc>(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<KanjiBloc>(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<KanjiBloc>(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,
),
);
}
}