Search code examples
firebaseflutterblocrxdart

Create user profile page using Bloc, RxDart and Flutter


My goal is to create an edit profile page in Flutter using the bloc pattern.

I've searched for a better/cleaner way to create a user profile page in Flutter using Bloc, but I can't find anything.

Right now I have to list every field out. Here's an example of 2 fields:

final _firstNameController = BehaviorSubject<String>();
final _lastNameController = BehaviorSubject<String>();

Function(String) get firstNameChanged => _firstNameController.sink.add;
Function(String) get lastNameChanged => _lastNameController.sink.add;

Stream<String> get firstNameStream => _firstNameController.stream;
Stream<String> get lastNameStream => _lastNameController.stream;

String get firstName => _firstNameController.value;
String get lastName => _lastNameController.value;


@override
  void dispose() {
_firstNameController?.close();
_lastNameController?.close();
}

There are a lot more fields and I don't want to have all this code if I can avoid it.

I'd prefer to only have 1 user bloc and update the specific field of that user. I've added the following to a user bloc.

final _userFetcher = BehaviorSubject<User>();

Observable<User> get userStream => _userFetcher.stream;
User get user => _userFetcher.value;
Function(User) get changeUser => _userFetcher.sink.add;

@override
  void dispose() async {
    await _userFetcher.drain();
    _userFetcher.close();
  }

Here's an example of my user model:

class User {

  final Name name;

  User.fromJson(Map<String, dynamic> json)
      : name = Name.fromJson(json);

  Map<String, dynamic> toJson() => {
    "first": name.first,
    "last": name.last,
  };
}

The issue is I can't figure out how to use a textfield to edit the "fist name" and "last name" fields in my "User" model.

Is this possible, am I going about this the wrong way, or should I stick to listing every field out individually?


Solution

  • Thank you everyone for your help!

    I ended up being able to edit the nested first and last name fields in my user model I listed above by implementing the following in my textField:

    onChanged:(text) {
            User thisUser = _bloc.user;
            thisUser.name.last = text;
          }