State의 mounted은 해당 위젯이 현재 위젯트리에 마운트(적용)되어 있는지 확인하는 키워드입니다.
리빌딩 작업이나 비동기 작업의 결과를 위젯에 적용시키기 전에 여전히 해당 위젯이 유효한 위젯인지 재차 확인하는 방식입니다.
if (mounted) {
setState(() {
...
})
}
mounted = false
- 화면에서 해당 위젯이 제거 되었음을 의미합니다.
mounted = true
- 화면이 해당 위젯에 여전히 유효함을 의미합니다.
void onButtonTapped(BuildContext context) async {
await Future.delayed(const Duration(seconds: 1));
Navigator.of(context).pop();
}
void onButtonTapped(BuildContext context) {
Navigator.of(context).pop();
}
void onButtonTapped(BuildContext context) async {
await Future.delayed(const Duration(seconds: 1));
if (!context.mounted) return;
Navigator.of(context).pop();
}
abstract class MyState extends State<MyWidget> {
void foo() async {
await Future.delayed(const Duration(seconds: 1));
if (!mounted) return; // Checks `this.mounted`, not `context.mounted`.
Navigator.of(context).pop();
}
}