How to Serialize object with XFile in Hydrated Bloc?

Viewed 131

I'm using image_picker plugin to get images from gallery.

I save that image(XFile) in an object with bunch of properties. My State of HydratedBloc has list of that object. What is the best way to store that XFile for HydratedBloc?

What is the best way to write toJson and fromJson functions for Expense class. I have two thoughts

  1. I can convert XFile object to base64 and then convert it back again in fromJson.
  2. I can write Xfile to ApplicationDocumentsDirectory as a File and then get it back from there to tmp storage on fromJson.

At second option, I have to delete permanent file from ApplicationDocumentsDirectory when I get back the file to tmp storage to avoid bloating storage of phone.

Codes are like below. My Object Expense

class Expense extends Equatable {
  final String companyName;
  final DateTime? date;
  final XFile? image;

  ...
  ...
}

ExpenseState

class ExpenseState extends Equatable {
  final List<Expense> expenses;

  const ExpenseState({required this.expenses});

  ...
}

ExpenseBloc

class ExpenseBloc extends HydratedBloc<ExpenseEvent, ExpenseState> {

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

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

}
0 Answers
Related