In my Flutter project, I am using Appwrite as a database (Alternate of Firebase).
When I try to fetch the collection
, it return the Instance of 'DocumentList'
but I am not able to decrypt the object into json format.
Here is the code:
import 'package:appwrite/appwrite.dart';
void main() { // Init SDK
Client client = Client();
Databases databases = Databases(client);
client
.setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
.setProject('5df5acd0d48c2') // Your project ID
;
Future result = databases.listDocuments(
databaseId: '[DATABASE_ID]',
collectionId: '[COLLECTION_ID]',
);
result
.then((response) {
print(response); // Instance of 'DocumentList'
}).catchError((error) {
print(error.response);
});
}
Here is the format of DocumentList
:
{
"total": 5,
"documents": [
{
"$id": "5e5ea5c16897e",
"$collectionId": "5e5ea5c15117e",
"$databaseId": "5e5ea5c15117e",
"$createdAt": "2020-10-15T06:38:00.000+00:00",
"$updatedAt": "2020-10-15T06:38:00.000+00:00",
"$permissions": [
"read(\"any\")"
]
}
]
}
How to handle the object & decrypt the response with model? please help.
The source code for DocumentList
is:
class DocumentList implements Model {
/// Total number of documents documents that matched your query.
final int total;
/// List of documents.
final List<Document> documents;
DocumentList({
required this.total,
required this.documents,
});
// omitted for brevity
}
As you can see, it has a documents
property so you can access it like response.documents
.
The source code for Document
is:
class Document implements Model {
/// Document ID.
final String $id;
/// Collection ID.
final String $collectionId;
/// Database ID.
final String $databaseId;
/// Document creation date in ISO 8601 format.
final String $createdAt;
/// Document update date in ISO 8601 format.
final String $updatedAt;
/// Document permissions. [Learn more about permissions](/docs/permissions).
final List $permissions;
final Map<String, dynamic> data;
Document({
required this.$id,
required this.$collectionId,
required this.$databaseId,
required this.$createdAt,
required this.$updatedAt,
required this.$permissions,
required this.data,
});
// omitted for brevity
}
In Document
, there's a data
property that contains the custom attributes you've added to your Collection. So, (assuming response.documents
has at least 1 Document
and the Collection has an Attribute with key myCustomAttribute
), you can do response.documents.first.data['myCustomAttribute']
.
As with any package or language you use, make sure to:
By the way, you only "decrypt" something that is encrypted. Typically, APIs return a JSON string and you "decode" it to convert it from a string to a map.