I made a chat page in my app. I want to paginate the data in upwards direction. I used refresh indicator for that event and then adding the data upwards. I am using a deque for displaying chats. So, whenever i display chats, i add them in front, and whenever i get a new chat from socket, i add them to back, hence maintaining my deque.
The problem with this is that whenever data gets added, my screen displays the latest fetched chats, as it should. First, check this code and then i will explain everything in detail at last:
class _IndividualChatPageState extends State<IndividualChatPage> {
final TextEditingController textEditingController = TextEditingController();
final ScrollController _scrollController = ScrollController();
final FocusNode focusNode = FocusNode();
bool _needsScroll = false;
double getWidth(int index) {
switch(index) {
case 0: return MediaQuery.of(context).size.width*0.7;
case 1: return MediaQuery.of(context).size.width*0.7;
case 2: return MediaQuery.of(context).size.width*0.2;
case 3: return MediaQuery.of(context).size.width*0.8;
case 4: return MediaQuery.of(context).size.width*0.4;
case 5: return MediaQuery.of(context).size.width*0.6;
default: return MediaQuery.of(context).size.width*0.4;
}
}
@override
void initState() {
super.initState();
fetchChats();
WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollController.addListener(_scrollListener);
});
_scrollToBottom();
}
void _scrollListener() {
if (_scrollController.position.pixels == _scrollController.position.minScrollExtent && context.read<ChatsBloc>().state.getIsPaginatingChats==false) {
context.read<ChatsBloc>().add(PaginateMoreChatsEvent(userId: widget.userId));
}
}
void _scrollToBottom() {
if (_scrollController.hasClients) {
_scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}
}
fetchChats() {
context.read<ChatsBloc>().add(EraseIndividualChatsEvent());
context.read<ChatsBloc>().add(FetchChatsEvent(userId: widget.userId));
_needsScroll=true;
}
void openSelectedFile({required String path}) {
String type = lookupMimeType(path)??"";
if(type.contains("image")) {
addImage(path: path);
} else if(type.contains("video")) {
addVideo(path: path);
} else if(type.contains("pdf")) {
addFile(path: path);
}
_needsScroll=true;
}
Future<void> addImage({required String path}) async {
final caption = await Navigator.pushNamed(context, MyRoute.photoViewerPage,
arguments: {
"path": path,
"show_send_option": true,
});
if(caption!=null && (caption is String)) {
context.read<ChatsBloc>().add(AddMessageEvent(
chatMessageData: ChatMessageData(
text: caption,
path: path,
isReply: false,
type: "image",
),
));
}
_needsScroll=true;
}
Future<void> addVideo({required String path}) async {
final caption = await Navigator.pushNamed(context, MyRoute.videoViewerPage,
arguments: {
"path": path,
"show_send_option": true,
});
if(caption!=null && (caption is String?)) {
context.read<ChatsBloc>().add(AddMessageEvent(
chatMessageData: ChatMessageData(
text: caption.toString(),
path: path,
isReply: false,
type: "video",
),
));
}
_needsScroll=true;
}
void addFile({required String path}) async {
final map = await Navigator.pushNamed(context, MyRoute.pdfViewerPage,
arguments: {
"path": path,
"show_send_option": true,
});
if(map!=null && map is Map<String, dynamic>) {
if((map["add_chat"] is bool) && map["add_chat"]==true) {
context.read<ChatsBloc>().add(SendMessageEvent(
chatMessageData: ChatMessageData(
text: map["message"],
path: path,
isReply: false,
type: "pdf",
),
));
}
_needsScroll=true;
} else {
showToast("Cannot add this file! Please try again");
}
}
void animateToEndOfList() {
if(_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 1),
curve: Curves.fastOutSlowIn,
);
}
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFf2f4f7),
body: Column(
children: [
Container(
height: 100,
alignment: Alignment.bottomCenter,
decoration: const BoxDecoration(
color: Colors.white,
),
child: Row(
children: [
IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(
Icons.close,
),
),
const Expanded(child: SizedBox()),
Container(
width: 36,
height: 36,
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(8),
),
),
const Padding(
padding: EdgeInsets.only(left: 8.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Ritu Dubey",
style: TextStyle(
color: Color(0xFF101828),
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
Text(
"English Teacher",
style: TextStyle(
color: Color(0xFF98a2b3),
fontSize: 10,
fontWeight: FontWeight.w500,
),
),
],
),
),
const Expanded(child: SizedBox()),
const Icon(
Icons.more_horiz,
color: Colors.transparent,
),
],
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: BlocBuilder<ChatsBloc, ChatsState>(
builder: (context, state) {
if(state.getLoadingChatsList==true) {
return ListView.builder(
itemCount: 12,
itemBuilder: (context, index) {
return ChatTileShimmer(
width: getWidth(index),
alignment: index%2==0 ? Alignment.centerLeft : null,
);
},
);
}
else if(state.getMessages.isEmpty) {
return const Center(
child: Text(
"Start a conversation",
),
);
}
else {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_needsScroll) {
_scrollToBottom();
_needsScroll = false;
}
});
return RefreshIndicator(
onRefresh: () async {
context.read<ChatsBloc>().add(PaginateMoreChatsEvent(userId: widget.userId));
},
child: ListView.builder(
controller: _scrollController,
itemCount: state.getMessages.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return ChatTile(
chatMessageData: state.getMessages.elementAt(index),
);
},
),
);
}
},
),
),
),
Container(
height: 60,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
color: Colors.white,
margin: const EdgeInsets.only(top: 8),
child: Row(
children: [
IconButton(
onPressed: () async {
FilePickerResult? pickedFile = await FilePicker.platform
.pickFiles(allowMultiple: false);
print("path of picked file: ${pickedFile?.files[0].path}");
if (pickedFile != null && context.mounted) {
openSelectedFile(path: pickedFile.files[0].path??"");
}
},
icon: const Icon(
Icons.attach_file,
color: AppColors.purpleColor,
size: 28,
),
),
Expanded(
child: TextField(
focusNode: focusNode,
controller: textEditingController,
style: const TextStyle(fontWeight: FontWeight.w500),
onTapOutside: (value) {
if(focusNode.hasFocus) {
focusNode.unfocus();
}
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(left: 16),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Color(0xFFeaecf0),
width: 1.5,
),
borderRadius: BorderRadius.circular(16),
),
border: OutlineInputBorder(
borderSide: const BorderSide(
color: Color(0xFFeaecf0),
width: 1.5,
),
borderRadius: BorderRadius.circular(16),
),
hintText: "Type...",
hintStyle: const TextStyle(fontWeight: FontWeight.w500, color: Color(0xFF98a2b3)),
suffixIcon: IconButton(
onPressed: () {
ChatMessageData chatMessageData = ChatMessageData(
text: textEditingController.text,
receiverId: 23147,
);
textEditingController.text="";
context.read<ChatsBloc>().add(SendMessageEvent(chatMessageData: chatMessageData));
context.read<ChatsBloc>().add(AddMessageEvent(chatMessageData: chatMessageData));
if(focusNode.hasFocus) {
focusNode.unfocus();
}
},
icon: const Icon(
Icons.send,
color: Color(0xFF344054),
),
),
),
),
),
IconButton(
onPressed: () async {
XFile? file = await ImagePicker()
.pickImage(source: ImageSource.camera);
if (file?.path != null) {
addImage(path: file?.path??"");
}
},
icon: const Icon(
Icons.camera_alt,
color: Color(0xFF667085),
),
),
],
),
)
],
),
);
}
}
Suppose I have chats loaded from index 0-14 in my first api call. Now, if i will go to the top, it will show me the chat at index 0. Now, if i will load new data, and them to my deque, then older chats will have index 15-29 and my new chats will have index 0-14 (I guess this is how deque works). Now, when those are loaded, it will show me chats from beginning, i.e. starting from index 0. I know this is how it should work, as it is remaining at it’s position and new data is just appearing there, and older data is going down. So, how can I fix this?
Also, whenever i am adding a new chat, it is not scrolling down to the latest chat. Please guide me with this. Like I don’t want to scroll down if a new chat has come from another user, but i want it to scroll down whenever i am adding a new chat.