I am trying to develop a mobile application with Flutter and AWS Amplify and I am new on the Amplify. There is a real-time messaging part in the application. My problem is that when the user selects a conversation on the screen, he/she will be able to see the messages with that person on the new page and at the beginning I want to pull the last 10 messages from the database. Then, as I scroll up the screen, I want to call the previous messages from the database 10 by 10. But I could not find the necessary parameters to do this in the ModelQueries.list method and I cannot do it.
I designed the model for it in graphql.schema as follows:
type Message @model @auth(rules: [{allow: private, operations: [read]}, {allow: owner}]) {
id: ID!
text: String!
visualDatas: [String]!
timestamp: AWSDateTime!
conversationID: ID! @index(name: "byConversation")
userID: ID! @index(name: "byUser")
}
type Conversation @model @auth(rules: [{allow: private, operations: [create, read]}]) {
id: ID!
members: [String]!
Messages: [Message] @hasMany(indexName: "byConversation", fields: ["id"])
}
I was able to do this with DataStore using the code, but I had to stop using DataStore due to some problems in the subscription method. And I’m currently trying to do it with the API, but I couldn’t succeed.
DataStore code I used before:
Future<List<Message>> getMessages({
required String conversationID,
}) async {
final messages = await Amplify.DataStore.query(Message.classType,
where: Message.CONVERSATIONID.eq(conversationID),
sortBy: [
const QuerySortBy(field: "createdAt", order: QuerySortOrder.ascending)
],
pagination: const QueryPagination(page: 0, limit: 10));
return messages;
}
API code I am using now:
Future<PaginatedResult<Message>?> getMessages({
required String conversationID,
}) async {
try {
final request = ModelQueries.list(
Message.classType,
where: Message.CONVERSATIONID.eq(conversationID),
limit: 10,
);
final response = await Amplify.API.query(request: request).response;
final firstPageMessages = response.data;
return firstPageMessages;
} on ApiException catch (e) {
safePrint('Query failed: $e');
}
return null;
}