Here we will see how to emit() List using flutter BLoC. BLoC state management emits any states and can be found from UI.
First we will create event classes.
abstract class ListEvents{}
class InitialListEvents extends ListEvents{}
class LoadedListEvents extends ListEvents{}
The event classes would be responsible triggering events.
Now let’s create state classes.
class LoadedList extends Equatable{
String title;
int age;
LoadedList({required this.title, required this.age});
@override
// TODO: implement props
List<Object?> get props => [title, age];
}
Here LoadedList extends Equitable class and it makes this class stateful. This also means we would be able to emit this class as state.
Whenever your class extends Equitable class, your class becomes stateful and you can emit.
Let’s create our BLoC class using the events and states.
class ListBLocs extends Bloc<ListEvents, List<LoadedList>>{
ListBLocs():super([]){
on<InitialListEvents>((events, states){
var info1 = LoadedList(title: "title1", age: 10);
var info2 = LoadedList(title: "title2", age: 20);
List<LoadedList> lists=[];
lists.add(info1);
lists.add(info2);
emit(lists);
});
}
}
Our ListBLocs extends Bloc and it takes ListEvents List<LoadedList>. So here we are saying our state is a List. It takes LoadedList class, so we are injecting List of classes.
and in the super class constructor we have empty List [].
Here inside on() method we are saying our event type is InitialListEvents.
We trigger the event from the UI and as we do it, we add items in the list. We added two items in the list. In your case you may add more items.
At the end we emit the lists.
void main() {
runApp( MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("BLocList App"),
),
body:BlocProvider(
create: (BuildContext context) {
return ListBLocs()..add(InitialListEvents());
},
child: BlocBuilder<ListBLocs, List<LoadedList>>(
builder: (context, state){
//print("${state[0].title}");
if(state.isNotEmpty){
print("${state[0].title.toString()}");
return Center(child: Container(child:Text("${state[1].title.toString()}")));
}
return Container();
},
)
)
),
);
}
}
In the UI BlocProvider, you can find your states. You see that we can print our certain states. In this case our states are lists.