0

I'm learning Bloc, but I'm having some trouble to save the data permanently. I Have this TextFormFieldenter image description here

where it comes with a name from an API, if I update this name, it should save, and show the update name in the other screens, like the Profile Screen an Editing Profile Screen, like the images below. enter image description here

enter image description here

enter image description hereugp5u.png

The problem is, I can save and update the name, but when I restart the app, it comes back to the previously name in the API, and I would like that this updates be saved permanently.

How can I do that? Here's my state class

    class FormNameState extends Equatable {

  final String nameForm;

  //FormNameState({required this.nameForm, this.formSubmited});
  FormNameState({required this.nameForm});

  @override
  List<Object?> get props => [nameForm];


  Map<String, dynamic> toMap() {
    return {
      'nameForm': nameForm,
    };
  }


  factory FormNameState.fromMap(Map<String, dynamic> map) {
    return FormNameState(
      nameForm: map['nameForm'],
    );
  }

  String toJson() => json.encode(toMap());

  factory FormNameState.fromJson(String source) =>
      FormNameState.fromMap(json.decode(source));
}

Event class

abstract class FormNameEvent extends Equatable {
  @override
  List<Object> get props => [];
}

class UpdateName extends FormNameEvent {
  final String nameForm;

  UpdateName({required this.nameForm});
}

class FormNameWithTester extends FormNameEvent {}

bloc class

class FormNameBloc extends HydratedBloc<FormNameEvent, FormNameState> {
  FormNameBloc(this.loginBloc) : super(FormNameState(nameForm: ''));
  final LoginBloc loginBloc;

  @override
  Stream<FormNameState> mapEventToState(FormNameEvent event) async* {
    print(event);
    if (event is UpdateName) {
      yield* _mapUpdateName(event);
    }
    /* if (event is FormNameWithTester) {
      yield* _mapUpda(event);
    } */
    //throw UnimplementedError('missingEvent');
  }

  Stream<FormNameState> _mapUpdateName(UpdateName event) async* {
    event.nameForm;
    loginBloc.add(FormEditionName(formName: event.nameForm));
    print('eventString');
    //yield state;
  }

  @override
  FormNameState fromJson(Map<String, dynamic> json) {
    return FormNameState.fromJson(json);
  }

  @override
  Map<String, dynamic> toJson(FormNameState state) {
    return state.toJson(state);
  }
}

1 Answers1

0

You would need to use Shared Preference to store data permanently, On app restart, you can get it back from it.