executeWithLoading function

Future<bool> executeWithLoading({
  1. required State<StatefulWidget> state,
  2. required void setLoading(
    1. bool
    ),
  3. void setError(
    1. String?
    )?,
  4. required Future<void> operation(),
})

Execute an async operation with automatic error handling and loading state.

Returns true if operation succeeded, false if failed.

Usage:

await executeWithLoading(
  state: this,
  setLoading: (loading) => _isLoading = loading,
  setError: (error) => _errorMessage = error,
  operation: () async {
    final data = await fetchData();
    _data = data;
  },
);

Implementation

Future<bool> executeWithLoading({
  required State state,
  required void Function(bool) setLoading,
  void Function(String?)? setError,
  required Future<void> Function() operation,
}) async {
  if (!state.mounted) return false;

  safeSetState(state, () {
    setLoading(true);
    setError?.call(null);
  });

  try {
    await operation();
    if (state.mounted) {
      // CRITICAL: Execute setState to trigger rebuild after operation completes.
      safeSetState(state, () => setLoading(false));
    }
    return true;
  } catch (e) {
    if (state.mounted) {
      safeSetState(state, () {
        setError?.call(e.toString());
        setLoading(false);
      });
    }
    return false;
  }
}