Home > Blockchain >  How to create a list with values ​from state?
How to create a list with values ​from state?

Time:06-04

In the application, when I click on the button, I write the name of the group in the field and add it to the database. The name of the group is also displayed on the screen. My problem is that every time I create a new group, it is overwritten on the screen. And I need to display the names of the groups on the screen as a list and so that it is added and not overwritten. But the implementation is such that in my state there is not a list and it is impossible to display the names of groups using map. How can I display the titles as a list so they don't get overwritten?

@immutable
abstract class NewGroupState {
  const NewGroupState();
  @override
  List<Object?> get props => [];
}
class NewGroupInitial extends NewGroupState {
  const NewGroupInitial();
}
class AddGroupState extends NewGroupState {
  const AddGroupState(this.group);
  final Group group;
}

body: BlocBuilder<NewGroupBloc, NewGroupState>(
  builder: (context, state) {
    return ListTile(
      title: Text(state is AddGroupState ? state.group.groupName : ''),
    );
  },
),

CodePudding user response:

I'm not sure I understood your question, is this what you're trying to do? If not, can you rewrite your question?

class AddGroupState extends NewGroupState {
  const AddGroupState(this.currentGroup, this.previousGroups);
  final Group currentCroup;
  final List<Group> previousGroups;
}
class NewGroupBloc extends Bloc<NewGroupState> {
    Future<void> addGroupToDB() async {
        final newGroup = Group();
        try {
            // add group to DB
            await _groupRepository.add(newGroup);
            final updatedGroups = [...state.previousGroups, newGroup];
            emit(NewGroupState(newGroup, updatedGroups));
        } on DBError catch (e) {
            emit(NewGroupErrorState());
        }
    }
}

Edit: this is a BAD answer but author asked how it could be done.

class NewGroupBloc extends Bloc<NewGroupState> {
    late Future<void> Function(Group group) onAddGroup;

    Future<void> addGroupToDB() async {
        final newGroup = Group();
        try {
            await _groupRepository.add(newGroup);
            await onAddGroup(newGroup);
            emit(NewGroupState(newGroup));
        } on DBError catch (e) {
            emit(NewGroupErrorState());
        }
    }
}
class _GroupPageState extends State<GroupPage> {
    var groups = <Group>[];
    NewGroupBloc bloc = // don't know how it was initialized

    @override
    void initState() {
        bloc.onAddGroup = (newGroup) {
            setState(() {
                groups = [...groups, newGroup];
            });
        }
    }

    Widget build(BuildContext context) {
        // The same as you already have, but using groups declared in the Widget instead of BLoC's state.
    }
}
  • Related