Skip to content

Instantly share code, notes, and snippets.

@AlexV525
Created June 8, 2022 10:09
Show Gist options
  • Save AlexV525/9a5bd66d14e0c9663af46be71119c60e to your computer and use it in GitHub Desktop.
Save AlexV525/9a5bd66d14e0c9663af46be71119c60e to your computer and use it in GitHub Desktop.
//
// [Author] Alex (https://github.com/AlexV525)
// [Date] 2020/9/15 14:06
//
import 'dart:async';
import 'package:flutter/widgets.dart';
extension SafeSetStateExtension on State {
/// [setState] when it's not building, then wait until next frame built.
FutureOr<void> safeSetState(FutureOr<dynamic> Function() fn) async {
await fn();
if (mounted &&
!context.debugDoingBuild &&
context.owner?.debugBuilding == false) {
// ignore: invalid_use_of_protected_member
setState(() {});
}
final Completer<void> completer = Completer<void>();
WidgetsBinding.instance.addPostFrameCallback((_) {
completer.complete();
});
return completer.future;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment