Created
June 8, 2022 10:09
-
-
Save AlexV525/9a5bd66d14e0c9663af46be71119c60e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// | |
// [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