Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Last active January 18, 2024 09:31
Show Gist options
  • Save wjkoh/f15d4805d61cad56308b047c592bba00 to your computer and use it in GitHub Desktop.
Save wjkoh/f15d4805d61cad56308b047c592bba00 to your computer and use it in GitHub Desktop.
Dart/Flutter: StatefulWidget + TextEditingController + FutureBuilder
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) {
...
}
);
}
}
@wjkoh
Copy link
Author

wjkoh commented Jan 18, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment