Last active
January 18, 2024 09:31
-
-
Save wjkoh/f15d4805d61cad56308b047c592bba00 to your computer and use it in GitHub Desktop.
Dart/Flutter: StatefulWidget + TextEditingController + FutureBuilder
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
class EditCaptionView extends StatefulWidget { | |
final String postId; | |
const EditCaptionView({super.key, required this.postId}); | |
@override | |
State<EditCaptionView> createState() => _EditCaptionViewState(); | |
} | |
class _EditCaptionViewState extends State<EditCaptionView> { | |
final _controller = TextEditingController(); | |
late final Future<PostModel?> _post; | |
@override | |
void initState() { | |
super.initState(); | |
_post = () async { | |
final post = await PostRepository().get(widget.postId); | |
// TODO: what if _controller is already disposed? | |
// I put this line here, not in build() or builder(), to avoid to get it called multiple times. | |
_controller.text = post?.caption.text ?? ''; | |
return post; | |
}(); | |
} | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return FutureBuilder<PostModel?>( | |
future: _post, | |
builder: (BuildContext context, AsyncSnapshot<PostModel?> snapshot) { | |
... | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check out https://stackoverflow.com/a/50337157