Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the state using hydated_bloc in flutter?

Tags:

flutter

bloc

I'm trying keep the state using the library hydrated_bloc, the problem is what all example of the this library are very basic and i want to maintain the state by consuming an example api rest but I still can't implement the logic of this example:

userbloc_bloc.dart

import 'dart:async';
import 'package:di/users/model/user.dart';
import 'package:di/users/repository/cloud_api_repository.dart';
import 'package:equatable/equatable.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';

part 'userbloc_event.dart';
part 'userbloc_state.dart';

class UserblocBloc extends HydratedBloc<UserblocEvent, UserblocState> {
  @override
  UserblocState get initialState {
     return super.initialState ?? UserblocInitial();

  }

    @override
  UserblocState fromJson(Map<String, dynamic> json) {
    try {
      final usermodel = UserModel.fromJson(json);
      return UserblocLoaded(usermodel);
    } catch (_) {
      return null;
    }
  }

  @override
  Map<String, dynamic> toJson(UserblocState state) {

    if (state is UserblocLoaded) {
      return state.userModel.toJson();
    }else{
      return null;
    }

  }

  @override
  Stream<UserblocState> mapEventToState(
    UserblocEvent event,
  ) async* {

  }


}

userbloc_state.dart

part of 'userbloc_bloc.dart';


abstract class UserblocState extends Equatable {
  UserblocState([List props = const[]]);
}

class UserblocInitial extends UserblocState {
   CloudApiRepository _cloudApiRepository;
  @override
  List<Object> get props => null;
  Future<UserModel> getlistUser() => _cloudApiRepository.getlistUser();
}

    class UserblocLoading extends UserblocState {
      @override
      Li

st<Object> get props => null;
}
class UserblocLoaded extends UserblocState {
  final UserModel userModel;
  UserblocLoaded(this.userModel);

  @override
  List<Object> get props => null;

}

HomeUser.dart

import 'package:di/users/bloc/userbloc/userbloc_bloc.dart';
import 'package:di/users/model/user.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomeUser extends StatefulWidget {
  HomeUser({Key key}) : super(key: key);

  @override
  _HomeUserState createState() => _HomeUserState();
}

class _HomeUserState extends State<HomeUser> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
          body: BlocProvider(create: (context) => UserblocBloc(),
          child: BlocBuilder<UserblocBloc, UserblocState>(
            builder: (BuildContext context, UserblocState state) {
              if (state is UserblocInitial) {
                return showanytext();
              } else if (state is UserblocLoading) {
                return buildLoading();
              } else if (state is UserblocLoaded) {
                return buildColumnWithData(state.userModel.data);
              }
            },
          ),
        ),
    );
  }
}

Widget buildColumnWithData(List<User> users){
  final user = users;

  return ListView.builder(
    itemCount: users.length,
    itemBuilder: (BuildContext context, int i){

      return Container(
        padding: EdgeInsets.all(15),
        child: Text("${user[i].firstName}", style: TextStyle(color:Colors.white),),
        decoration: BoxDecoration(
          color: Colors.black
        ),
      );
    });
}
Widget buildLoading(){

  return Center(
    child: Container(
      child: CircularProgressIndicator(),
    ),
  );
}

Widget showanytext(){

  return Center(
    child: Container(
      child: Text("Construyendo el widget"),
    ),
  );
}

Some idea of how I can keep the state of my pad consuming an api in such a way that if I close the app and reopen it in the same place in leaving her the last time I close her

like image 573
Steven Colocho Avatar asked Apr 19 '20 04:04

Steven Colocho


1 Answers

Great question - I have a very similar problem.

In short - my Cubit's States reflect the stages of filling out and sending a form to the API: - Initial, - Started, -Tick, - Completed and - Sent.

Since it is impossible to determine which state should be returned by the Hydrated Bloc functionality I am actually adding the state property to the Cubit State as an enum to reflect the state in which the Cubit 'was last seen' and on some conditions return the same state from the repository. With it the last filled out fields will be fetched. This sounds and looks like a redundancy but I could not think of a better solution. I would be more than happy to hear some ideas :)

Here is the Cubit's State class declaration:

part of 'job_realization_cubit.dart';

enum Status {
  initial,
  started,
  tick,
  completed,
  sent,
}

abstract class JobRealizationState extends Equatable {
  const JobRealizationState({
    this.status,
    this.timeLeft,
    this.jobRealization,
    this.message,
  });
  final Status status;
  final int timeLeft;
  final JobRealization jobRealization;
  final String message;

  @override
  List<Object> get props => [status, timeLeft, jobRealization, message];
}

class JobRealizationInitial extends JobRealizationState {
  const JobRealizationInitial();
}

class JobRealizationStarted extends JobRealizationState {
  const JobRealizationStarted({status, timeLeft, jobRealization, message})
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );
}

//Timekeeping after start of Realization
class JobRealizationTick extends JobRealizationState {
  const JobRealizationTick({status, timeLeft, jobRealization, message})
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );
}


class JobRealizationDone extends JobRealizationState {
  const JobRealizationDone({status, timeLeft, jobRealization, message})
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );
}

class JobRealizationSent extends JobRealizationState {
  const JobRealizationSent({status, timeLeft, jobRealization, message})
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );
}

class JobRealizationSendError extends JobRealizationState {
  const JobRealizationSendError({status, timeLeft, jobRealization, message})
      : super(
          status: status,
          timeLeft: timeLeft,
          jobRealization: jobRealization,
          message: message,
        );
}
like image 192
Łukasz Garczynski Avatar answered Sep 18 '22 08:09

Łukasz Garczynski