I am trying to implement a dynamic list view in flutter which could be increased by tapping the floating actin button. But the method in onPressed of floating action button is being updated only once.
Below is my code for both the UI and flutter bloc:-
import 'package:demo/bloc/main/demo_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Demo",
home: DemoApp(),
);
}
}
class DemoApp extends StatelessWidget {
const DemoApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
lazy: false,
create: (context)=>DemoBloc([54,4,598,984,654,87,5,897,65,46,84,65,4984,]),
child: Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
body: NumberList(),
floatingActionButton: BlocBuilder<DemoBloc, List<int>>(
builder: (context, state){
return FloatingActionButton(
onPressed: (){
BlocProvider.of<DemoBloc>(context).addItem(12);
}
);
},
),
),
);
}
}
class NumberList extends StatelessWidget {
const NumberList({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocBuilder<DemoBloc, List<int>>(builder: (context, state) {
return ListView.builder(
itemCount: BlocProvider.of<DemoBloc>(context).state.length,
itemBuilder: (context, index) {
return Text(
BlocProvider.of<DemoBloc>(context).state[index].toString()
);
});
});
}
}
import 'package:flutter_bloc/flutter_bloc.dart';
class DemoBloc extends Cubit<List<int>>{
DemoBloc(List<int> initialState) : super(initialState);
addItem(int value){
print("adding item to the numbers list");
state.add(value);
emit(state);
}
removeItem(){
state.removeLast();
emit(state);
}
removeItemFrom(int index){
state.removeAt(index);
emit(state);
}
}
I am using print function inside addItem() function and it is executing and being printed in the console , but the list is not being updated except only once.