When added new items to list using bloc in listview, listview rebuild and automatically get back to top and also blinks.
Don't figure out what is the problem excatly. Does is necessary to use PageStorageKey or it can be done without PageStorageKey too. Because with page storage key scroll position is saved but listview is blinking.
If anyone have solution then please answer.
class MessageListScreen extends StatefulWidget {
static const routeName = "message_list_screen";
final Day? day;
const MessageListScreen({Key? key, this.day}) : super(key: key);
@override
State<MessageListScreen> createState() => _MessageListScreenState();
}
class _MessageListScreenState extends State<MessageListScreen> {
late ScrollController _scrollController;
@override
void initState() {
super.initState();
print(widget.day);
_scrollController = ScrollController();
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
_getMessages();
});
}
bool _handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollEndNotification) {
if (_scrollController.position.extentAfter == 0) {
_getMessages();
}
}
return false;
}
void _getMessages() {
String? dayId = widget.day?.sId;
if (dayId != null) context.read<GetMessagesCubit>().getMessages(dayId);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: AppbarTitleWidget(widget.day?.day ?? "Messages"),
),
body: Container(
child: BlocBuilder<GetMessagesCubit, GetMessagesState>(
builder: (context, state) {
if (state is GetMessagesLoaded) {
print("SIZEEEE ${state.getMessagesResponse?.data?.messages?.length}");
return NotificationListener<ScrollNotification>(
onNotification: _handleScrollNotification,
child: ListView.builder(
controller: _scrollController,
itemCount: state.getMessagesResponse?.data?.messages?.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(10),
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor.withAlpha(90),
border:
Border.all(color: Theme.of(context).primaryColor),
borderRadius: BorderRadius.all(Radius.circular(10))),
child: Text(
state.getMessagesResponse?.data?.messages?[index].message ?? "",
style: Theme.of(context).textTheme.bodyText2,
),
);
},
),
);
} else {
return LoadingWidget();
}
},
),
),
),
);
}
@override
void dispose() {
super.dispose();
_scrollController.dispose();
context.read<GetMessagesCubit>().close();
}
}