import 'dart:async'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../../../core/network/error_message.dart'; import '../data/profile_repository_impl.dart'; import '../domain/profile_models.dart'; part 'profile_controller.g.dart'; @riverpod class ProfileController extends _$ProfileController { bool _active = true; int _generation = 0; @override ProfileState build() { _active = true; ref.onDispose(() => _active = false); unawaited(Future.microtask(reload)); return const ProfileState(); } Future reload() async { if (!_active || state.saving) return; final generation = ++_generation; state = state.copyWith(loading: true, alert: null, issue: null); try { final profile = await ref.read(profileRepositoryProvider).load(); if (_active && generation == _generation) { state = state.copyWith(profile: profile, loading: false); } } catch (_) { if (_active && generation == _generation) { state = state.copyWith(loading: false); } } } Future save(String nickname, String signature) async { if (state.saving) return false; final name = nickname.trim(); if (name.isEmpty || name.length > 64) { state = state.copyWith(issue: ProfileIssue.nicknameInvalid); return false; } if (signature.trim().length > 200) { state = state.copyWith(issue: ProfileIssue.signatureInvalid); return false; } return _write( () => ref.read(profileRepositoryProvider).save(name, signature.trim()), ); } Future changeAvatar() async { await _write(() => ref.read(profileRepositoryProvider).chooseAvatar()); } Future _write(Future Function() action) async { if (state.saving) return false; ++_generation; state = state.copyWith( saving: true, loading: false, alert: null, issue: null, ); try { final profile = await action(); if (!_active) return false; state = state.copyWith(profile: profile ?? state.profile, saving: false); return profile != null; } on ProfileInputException catch (error) { if (_active) state = state.copyWith(saving: false, issue: error.issue); return false; } catch (error) { if (_active) { state = state.copyWith(saving: false, alert: userMessageOf(error)); } return false; } } void consumeAlert() => state = state.copyWith(alert: null, issue: null); }