From 942f61d90d7f83d3a92fc4f972de859a1f11de1b Mon Sep 17 00:00:00 2001 From: Ming Ming <nkming2@gmail.com> Date: Sun, 25 Jul 2021 19:41:05 +0800 Subject: [PATCH] Fix text field value not preserved after scrolling --- lib/widget/album_viewer_app_bar.dart | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/lib/widget/album_viewer_app_bar.dart b/lib/widget/album_viewer_app_bar.dart index e9d12469..e1025350 100644 --- a/lib/widget/album_viewer_app_bar.dart +++ b/lib/widget/album_viewer_app_bar.dart @@ -66,7 +66,7 @@ class _AlbumViewerEditAppBarState extends State<AlbumViewerEditAppBar> { @override initState() { super.initState(); - _editNameValue = widget.album.name; + _controller = TextEditingController(text: widget.album.name); } @override @@ -78,28 +78,25 @@ class _AlbumViewerEditAppBarState extends State<AlbumViewerEditAppBar> { background: _getAppBarCover(context, widget.account, widget.coverPreviewUrl), title: TextFormField( + controller: _controller, decoration: InputDecoration( hintText: L10n.of(context).nameInputHint, ), - validator: (value) { - if (value?.isNotEmpty == true) { + validator: (_) { + // use _controller.text here because the value might be wrong if + // user scrolled the app bar off screen + if (_controller.text.isNotEmpty == true) { return null; } else { return L10n.of(context).albumNameInputInvalidEmpty; } }, - onSaved: (value) { - widget.onAlbumNameSaved?.call(value!); - }, - onChanged: (value) { - // need to save the value otherwise it'll return to the initial - // after scrolling out of the view - _editNameValue = value; + onSaved: (_) { + widget.onAlbumNameSaved?.call(_controller.text); }, style: TextStyle( color: AppTheme.getPrimaryTextColor(context), ), - initialValue: _editNameValue, ), ), leading: IconButton( @@ -112,7 +109,7 @@ class _AlbumViewerEditAppBarState extends State<AlbumViewerEditAppBar> { ); } - late String _editNameValue; + late TextEditingController _controller; } Widget? _getAppBarCover(