// Dart imports:
import 'dart:async';

// Flutter imports:
import 'package:flutter/material.dart';

extension StateExtension 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, no-empty-block
      setState(() {});
    }

    final Completer<void> completer = Completer<void>();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      completer.complete();
    });

    return completer.future;
  }
}
