Flutter BloC模式:基于另一个BloC的流更新BloC流

时间:2018-12-25 00:08:47

标签: dart flutter bloc

场景

我正在尝试创建一个具有两个屏幕的Flutter应用:ContactsScreenEditContactScreen。在ContactsScreen中,将向用户显示DropdownButtonTextDropdownButton包含通过API提取的Contact个对象的列表。每当用户从Contact中选择DropdownButton时,Text对象都会显示有关该特定联系人的信息。此外,在选择Contact时,将出现一个RaisedButton,当单击该EditContactScreen时,它将引导用户到Contact以编辑所选的ContactsScreenBloc。我正在使用BloC模式。我创建了两个BloC,每个屏幕一个:EditContactScreenBlocContactsScreenBlocStream<Contact>拥有一个Sink<Contact>和一个Contact,用于管理所选的EditContactScreenBlocContact保留GlobalBloc字段的流和接收器。最后,我有一个Contact,其中包含GlobalBloc的列表。 InheritedWidget是包裹MaterialApp的{​​{1}}。该应用程序过于简化,属于较大的应用程序,因此,我无法合并ContactsScreenBlocEditContactScreenBloc,并且应该有一个GlobalBloc,其中包含{{ 1}} s。

问题

我实际上对Flutter还是很陌生,所以我不确定我的方法是否正确。如果是,那么当用户导航到Contact并成功更新EditContactScreen时,如何将其反映回Contact中所选的Contact中?

代码快照

contact.dart

ContactsScreen

global.bloc.dart

class Contact {
  final String id;
  final String firstName;
  final String lastName;
  final String phoneNumber;

  Contact({this.id, this.firstName, this.lastName, this.phoneNumber});
  Contact.fromJson(Map<String, dynamic> parsedJson)
        : id = parsedJson['id'],
          firstName = parsedJson['firstName'],
          lastName = parsedJson['lastName'],
          phoneNumber = parsedJson['phoneNumber'];

  copyWith({String firstName, String lastName, String phoneNumber}) => Contact(
    id: id,
    firstName: firstName ?? this.firstName,
    lastName: lastName ?? this.lastName,
    phoneNumber: phoneNumber ?? this.phoneNumber
  );

  @override
  bool operator ==(other) => other.id == this.id;

  @override
  int get hashCode => id.hashCode;
}

contacts_screen.bloc.dart

class GlobalBloc {
  final _repo = Repo();

  final _contacts = BehaviorSubject<List<Contact>>(seedValue: []);

  Stream<List<Contact>> get contacts => _contacts.stream;

  Function(List<Contact>) get updateContacts => _contacts.sink.add;

  Future refreshContacts() async{
    final contacts = await _repo.getContacts();
    updateContacts(contacts);
  }
}

edit_contacts_screen.bloc.dart

class ContactsScreenBloc {
  final _selectedContact = BehaviorSubject<Contact>(seedValue: null);

  Stream<Contact> get selectedContact => _selectedContact.stream;

  Function(Contact) get changeSelectedContact => _selectedContact.sink.add;
}

global.provider.dart

class ContactsScreenBloc {
  final _selectedContact = BehaviorSubject<Contact>(seedValue: null);

  Stream<Contact> get selectedContact => _selectedContact.stream;

  Function(Contact) get changeSelectedContact => _selectedContact.sink.add;
}

contacts.screen.dart

class GlobalProvider extends InheritedWidget {
  final bloc = GlobalBloc();
  static GlobalBloc of(BuildContext context) => (context.inheritFromWidgetOfExactType(GlobalProvider) as GlobalProvider).bloc;
  bool updateShouldNotify(_) => true;
}

edit_contact.screen.dart

class ContactsScreen extends StatelessWidget {
  final bloc = ContactsScreenBloc();

  @override
  Widget build(BuildContext context) {
    final globalBloc = GlobalProvider.of(context);

    return Column(
      children: <Widget>[
        StreamBuilder<List<Contact>>(
          stream: globalBloc.contacts,
          builder: (context, listSnapshot) {
            return StreamBuilder<Contact>(
              stream: bloc.selectedContact,
              builder: (context, itemSnapshot) {
                return DropdownButton<Contact>(
                  items: listSnapshot.data
                      ?.map(
                        (contact) => DropdownMenuItem<Contact>(
                              value: contact,
                              child: Text(contact.firstName + ' ' + contact.lastName),
                            ),
                      )
                      ?.toList(),
                  onChanged: bloc.changeSelectedContact,
                  hint: Text('Choose a contact.'),
                  value: itemSnapshot.hasData ? itemSnapshot.data : null,
                );
              },
            );
          },
        ), // end for DropdownButton StreamBuilder

        StreamBuilder<Contact>(
          stream: bloc.selectedContact,
          builder: (context, snapshot) {
            return snapshot.hasData
                ? Row(children: <Widget>[
                Text(snapshot.data.firstName + ' ' + snapshot.data.lastName + ' ' + snapshot.data.phoneNumber),
                FlatButton(
                  child: Text('Edit Contact'),
                  onPressed: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (context) =>
                            EditContactScreen(contact: snapshot.data)));
                  },
                ),
              ],
            )
                : null;
          }, // End for text description
        )
      ],
    );
  }
}

1 个答案:

答案 0 :(得分:1)

好的,我能够解决我的问题:

contacts_screen.bloc.dart中,我添加了以下方法:

void updateContactInfo(List<Contact> contacts) {
    final contact = _selectedContact.value;
    if (contact == null) return;
    final updatedContact = contacts.firstWhere((a) => a.id == contact.id);
    if (updatedContact == null) return;
    changeSelectedContact(updatedContact);
  }

并更新了StreamBuilder<List<Contact>>以构建DropdownButton,如下所示:

StreamBuilder<List<Contact>>(
  stream: globalBloc.contacts,
  builder: (context, listSnapshot) {
    bloc.updateContactInfo(listSnapshot.data);
    return StreamBuilder<Contact>(
      stream: bloc.selectedContact,
      builder: (context, itemSnapshot) {
        return DropdownButton<Contact>(
          items: listSnapshot.data
              ?.map(
                (contact) => DropdownMenuItem<Contact>(
                      value: contact,
                      child: Text(
                          contact.firstName + ' ' + contact.lastName),
                    ),
              )
              ?.toList(),
          onChanged: bloc.changeSelectedContact,
          hint: Text('Choose a contact.'),
          value: itemSnapshot.hasData ? itemSnapshot.data : null,
        );
      },
    );
  },
)