Skip to content
Snippets Groups Projects
data_statistics_global_cubit.dart 1.95 KiB
Newer Older
Benoît Harrault's avatar
Benoît Harrault committed
import 'package:flutter/material.dart';
import 'package:flutter_custom_toolbox/flutter_toolbox.dart';
import 'package:scrobbles/models/data/statistics_global.dart';
import 'package:scrobbles/network/scrobbles.dart';
Benoît Harrault's avatar
Benoît Harrault committed

part 'data_statistics_global_state.dart';

class DataStatisticsGlobalCubit extends HydratedCubit<DataStatisticsGlobalState> {
  DataStatisticsGlobalCubit()
      : super(const DataStatisticsGlobalState(
          statisticsGlobal: null,
          status: '',
        ));
  void setLoading() {
    emit(DataStatisticsGlobalState(
      statisticsGlobal: state.statisticsGlobal,
      status: 'loading',
    ));
  }

  void setValue(StatisticsGlobalData? statisticsGlobal) {
    emit(DataStatisticsGlobalState(
      statisticsGlobal: statisticsGlobal,
      status: '',
    ));
  }

  void setFailed() {
    emit(DataStatisticsGlobalState(
      statisticsGlobal: state.statisticsGlobal,
      status: 'failed',
    ));
  void setLoaded() {
    emit(DataStatisticsGlobalState(
      statisticsGlobal: state.statisticsGlobal,
      status: '',
    ));
  void update(StatisticsGlobalData? statisticsGlobal) {
    if ((statisticsGlobal != null) &&
        (state.statisticsGlobal.toString() != statisticsGlobal.toString())) {
      setValue(statisticsGlobal);
    } else {
      setLoaded();
  void refresh(BuildContext context) async {
    setLoading();

    final StatisticsGlobalData? data = await ScrobblesApi.fetchGlobalStatistics();
    if (data != null) {
      update(data);
    } else {
      setFailed();
    }
Benoît Harrault's avatar
Benoît Harrault committed
  }

  @override
  DataStatisticsGlobalState? fromJson(Map<String, dynamic> json) {
    return DataStatisticsGlobalState(
      statisticsGlobal: StatisticsGlobalData.fromJson(json['statisticsGlobal']),
      status: '',
Benoît Harrault's avatar
Benoît Harrault committed
    );
  }

  @override
  Map<String, Object?>? toJson(DataStatisticsGlobalState state) {
    return <String, Object?>{
      'statisticsGlobal': state.statisticsGlobal?.toJson(),
      'status': state.status,