refactor(bootstapper): migration to riverpod

This commit is contained in:
hdbg
2025-12-17 20:03:18 +01:00
parent 31981fb19e
commit d7ec54d8ca
68 changed files with 4004 additions and 776 deletions

View File

@@ -2,12 +2,14 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:mtcore/markettakers.dart';
import 'package:mtcore/src/loader.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'bootstrapper.g.dart';
part 'bootstrapper.freezed.dart';
abstract class StageFactory {
@@ -25,121 +27,86 @@ sealed class Progress with _$Progress {
const factory Progress.indefinite() = IndefiniteProgress;
}
@freezed
class StageState with _$StageState {
final String title;
final Progress progress;
class StageState {
String title;
Progress progress;
StageState({required this.title, required this.progress});
}
class StageController extends Cubit<StageState> {
StageController({required String title})
: super(StageState(title: title, progress: const Progress.indefinite()));
typedef Stages = List<StageFactory>;
@riverpod
class CurrentStage extends _$CurrentStage {
@override
StageState? build() {
return null;
}
void set(StageState newState) {
state = newState;
}
void setProgress(Progress progress) {
state?.progress = progress;
}
void setTitle(String title) {
state?.title = title;
}
}
class StageController {
final Ref _ref;
StageController(this._ref);
void setDefiniteProgress(double value) {
emit(state.copyWith(progress: Progress.definite(value)));
if (!_ref.mounted) return;
_ref
.read(currentStageProvider.notifier)
.setProgress(Progress.definite(value));
}
void setIndefiniteProgress() {
emit(state.copyWith(progress: const Progress.indefinite()));
if (!_ref.mounted) return;
_ref.read(currentStageProvider.notifier).setProgress(Progress.indefinite());
}
void updateTitle(String title) {
emit(state.copyWith(title: title));
if (!_ref.mounted) return;
_ref.read(currentStageProvider.notifier).setTitle(title);
}
}
typedef Stages = List<StageFactory>;
@riverpod
class StagesWorker extends _$StagesWorker {
bool _hasStarted = false;
@freezed
class BootstrapState with _$BootstrapState {
final Stages stages;
final int currentStageIndex;
final StageController? controller;
StageFactory get currentStage => stages[currentStageIndex];
bool get areStagesCompleted => currentStageIndex >= stages.length;
BootstrapState(this.stages, {this.currentStageIndex = 0, this.controller});
}
@freezed
sealed class _BootstrapEvent with _$BootstrapEvent {
const factory _BootstrapEvent.start() = StartEvent;
const factory _BootstrapEvent.stageCompleted() = StageCompletedEvent;
}
class _BootstrapController extends Bloc<_BootstrapEvent, BootstrapState> {
final Completer<void> completer;
_BootstrapController(super.initialState, this.completer) {
assert(state.stages.isNotEmpty, "Stages list cannot be empty");
on<StartEvent>((event, emit) async {
talker.info("BootstrapController: Starting bootstrap process");
if (await state.currentStage.isAlreadyCompleted) {
add(const _BootstrapEvent.stageCompleted());
return;
}
final controller = launchCurrentStage(
state.stages,
state.currentStageIndex,
);
emit(state.copyWith(controller: controller));
});
on<StageCompletedEvent>((event, emit) async {
talker.info("BootstrapController: ${state.currentStage.title} completed");
state.currentStage.dispose();
final nextIndex = state.currentStageIndex + 1;
final newState = state.copyWith(currentStageIndex: nextIndex);
// all stages completed
if (newState.areStagesCompleted) {
talker.info("BootstrapController: All stages completed");
completer.complete();
return;
}
// skip already completed stages
if (await newState.currentStage.isAlreadyCompleted) {
talker.info(
"BootstrapController: Stage ${newState.currentStage.title} already completed, skipping",
);
emit(newState);
add(const _BootstrapEvent.stageCompleted());
return;
}
// move to next stage
final nextStage = newState.currentStage;
talker.info("BootstrapController: Starting stage ${nextStage.title}");
launchCurrentStage(state.stages, nextIndex);
emit(newState);
});
Future<bool> build() async {
return false;
}
StageController launchCurrentStage(Stages stages, int index) {
final currentStage = stages[index];
final controller = StageController(title: currentStage.title);
void start(Stages stages) async {
if (_hasStarted) return;
_hasStarted = true;
currentStage
.start(controller)
.then((_) {
add(_BootstrapEvent.stageCompleted());
})
.catchError((error) {
talker.handle(
error,
null,
"BootstrapController: Error in ${currentStage.title}",
);
addError(error);
});
state = AsyncValue.loading();
state = await AsyncValue.guard(() async {
for (final stage in stages) {
talker.info("${stage.title} starting");
return controller;
ref
.read(currentStageProvider.notifier)
.set(
StageState(title: stage.title, progress: Progress.indefinite()),
);
await stage.start(StageController(ref));
talker.info("${stage.title} completed");
}
return true;
});
}
}
@@ -150,63 +117,61 @@ class _DefiniteIndicator extends StatelessWidget {
@override
Widget build(BuildContext context) {
final formattedProgress = "${(progress * 100).toStringAsFixed(0)}%";
return CircularPercentIndicator(
radius: 40.0,
lineWidth: 5.0,
percent: progress.clamp(0.0, 1.0),
center: Text(formattedProgress),
progressColor: Theme.of(context).colorScheme.secondary,
final value = progress.clamp(0.0, 1.0);
return LayoutBuilder(
builder: (context, c) {
final side = (c.hasBoundedWidth && c.hasBoundedHeight)
? (c.maxWidth < c.maxHeight ? c.maxWidth : c.maxHeight)
: 80.0; // sensible fallback if unconstrained
final radius = side / 2;
final formattedProgress = "${(progress * 100).toStringAsFixed(0)}%";
return CircularPercentIndicator(
radius: radius * 2,
lineWidth: 5.0,
percent: value,
center: Text(formattedProgress),
progressColor: Theme.of(context).colorScheme.secondary,
);
},
);
// return CircularProgressIndicator(value: value);
}
}
class _BootstrapFooter extends StatelessWidget {
class _BootstrapFooter extends ConsumerWidget {
const _BootstrapFooter();
@override
Widget build(BuildContext context) {
return BlocBuilder<_BootstrapController, BootstrapState>(
builder: (context, state) {
if (state.areStagesCompleted) {
return Text(
"All stages completed",
style: Theme.of(context).textTheme.titleMedium,
);
} else if (state.controller != null) {
return BlocBuilder<StageController, StageState>(
bloc: state.controller,
builder: (context, state) {
final progressIndicator = state.progress.when(
definite: (definite) => _DefiniteIndicator(progress: definite),
indefinite: () => const CircularProgressIndicator(),
);
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(currentStageProvider);
if (state == null) return Container();
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Flexible(
flex: 1,
child: Text(
state.title,
style: Theme.of(context).textTheme.titleLarge,
),
),
Flexible(flex: 1, child: progressIndicator),
],
);
},
);
} else {
return const SizedBox.shrink();
}
},
final progressIndicator = state.progress.when(
definite: (definite) => _DefiniteIndicator(progress: definite),
indefinite: () => SpinKitCubeGrid(color: Colors.white),
);
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Flexible(
flex: 1,
child: Text(
state.title,
style: Theme.of(context).textTheme.titleLarge,
),
),
Flexible(flex: 1, child: progressIndicator),
],
);
}
}
class Bootstrapper extends StatelessWidget {
class Bootstrapper extends HookConsumerWidget {
final Stages stages;
final Completer onCompleted;
@@ -217,36 +182,27 @@ class Bootstrapper extends StatelessWidget {
});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) {
final controller = _BootstrapController(
BootstrapState(stages),
onCompleted,
);
controller.add(const _BootstrapEvent.start());
return controller;
},
child: BlocListener<_BootstrapController, BootstrapState>(
listener: (context, state) {
if (state.areStagesCompleted) {
onCompleted.complete();
}
},
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
flex: 2,
child: Center(child: Loader.playing(flavour: LoaderFlavour.big)),
),
Flexible(flex: 1, child: Container()),
Flexible(flex: 1, child: _BootstrapFooter()),
Flexible(flex: 1, child: Container()),
],
Widget build(BuildContext context, WidgetRef ref) {
Future(() async => ref.read(stagesWorkerProvider.notifier).start(stages));
final work = ref.watch(stagesWorkerProvider);
if (!onCompleted.isCompleted) {
if (work.hasError) onCompleted.completeError(work.error!);
if (work.hasValue && work.value!) onCompleted.complete();
}
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Flexible(
flex: 2,
child: Center(child: Loader.playing(flavour: LoaderFlavour.big)),
),
),
Flexible(flex: 1, child: Container()),
Flexible(flex: 1, child: _BootstrapFooter()),
Flexible(flex: 1, child: Container()),
],
);
}
}