Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dreampowder/72b9ce7f480a99ff1a73935e0df15731 to your computer and use it in GitHub Desktop.
Save dreampowder/72b9ce7f480a99ff1a73935e0df15731 to your computer and use it in GitHub Desktop.
An example for Bloc users to use with infinite_scroll_pagination 5.0.0
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:infinite_bloc_example/bloc/pagination_bloc.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'model/ItemModel.dart';
class ScreenMain extends StatefulWidget {
const ScreenMain({super.key});
@override
State<ScreenMain> createState() => _ScreenMainState();
}
class _ScreenMainState extends State<ScreenMain> {
final PaginationBloc _bloc = PaginationBloc();
PagingState<int, ItemModel> pagingState = PagingState();
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocListener<PaginationBloc,PaginationState>(
bloc: _bloc,
listener: (context, state){
if (state is PaginationStateDidReceivePagingState) {
setState(() {
this.pagingState = state.state;
});
}
},
child: PagedListView<int, ItemModel>(
state: pagingState,
fetchNextPage: (){
if (pagingState.hasNextPage) {
debugPrint("On Get Next Page");
_bloc.add(PaginationEventGetPage(pagingState));
}else{
debugPrint("Has no more page");
}
},
builderDelegate: PagedChildBuilderDelegate<ItemModel>(
itemBuilder: (context, item, index){
return ListTile(
title: Text(item.title),
);
}
)
),
),
);
}
}
class PaginationBloc extends Bloc<PaginationEvent, PaginationState> {
PaginationBloc() : super(PaginationInitial()) {
//on<PaginationEvent>((event, emit) {
//
// });
on<PaginationEventGetPage>(_getPage);
}
FutureOr<void> _getPage(PaginationEventGetPage event, Emitter<PaginationState> emit) async{
var paginationState = event.state;
emit(PaginationStateDidReceivePagingState(paginationState.copyWith(isLoading: true)));
await Future.delayed(Duration(seconds: 2));
var nextPage = (paginationState.keys?.last ?? 0) + 1;
List<List<ItemModel>> loadedItems = List.from(paginationState.pages ?? []);
var totalItems = paginationState.items?.length ?? 0;
loadedItems.add(List.generate(10, (i)=>ItemModel(i + totalItems)));
List<int> loadedKeys = List.from((paginationState.keys ?? []))..add(nextPage);
var updatedState = paginationState.copyWith(
pages: loadedItems,
keys: loadedKeys,
isLoading: false,
);
emit(PaginationStateDidReceivePagingState(updatedState));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment