Back

[Solved] Socket exception

  • 0
  • Databases
  • Flutter
nebukadnezar
15 Nov, 2023, 21:13

I get a socket exception err when I call the listDocuments() method.

Here's the code I use in Flutter to query:

TypeScript
Future<List<Document>> getNotes() async {
    DocumentList allNotes = await appwriteDatabase.listDocuments(
      databaseId: dojoDatabaseId,
      collectionId: noteCollectionId,
      queries: [
        Query.select([
          'subject',
          'description',
          'date',

          'id',
          //Permission is tijdelijk vanwege een bug in de SDK
          '\$permissions'
        ]),
        Query.orderDesc('date'),
      ],
    );
    return allNotes.documents;
  }```

Strangely enough when I turn off catch all exceptions in VS code; It ignores the exception. When I press a button which calls the method a second time it works 🫣 . Any ideas?

I tried the solution mentioned here: https://discord.com/channels/564160730845151244/1166669095639466074
TL;DR
User encountered a socket exception when calling the `listDocuments()` method in Flutter. They initially thought it was due to their programming skills, but later realized that the `addNote/createNote` method was not `async`. User also noticed that the print statement in the `getNotes()` method returned 5 documents instead of the expected 6. They speculated that using RealTime instead of async Futures might be a solution, but weren't sure. User also mentioned that they manually added permissions for internet, but it didn't solve the issue. They questioned if this step was necessary as Flutter handles certain exceptions during runtime. User provided relevant code snippets
Drake
15 Nov, 2023, 21:39

How are you initializing appwriteDatabase?

nebukadnezar
15 Nov, 2023, 22:04

This is the implementation:

TypeScript
 // init the client
  void _initClient() {
    appwriteClient
        .setEndpoint(apiEndpoint)
        .setProject(projectId)
        .setSelfSigned(status: true);
  }```
nebukadnezar
15 Nov, 2023, 22:05

And I use the main method's initState to init appwrite:

TypeScript
void main() {
  runApp(
    const Yushinkan(),
  );
}

class Yushinkan extends StatefulWidget {
  const Yushinkan({super.key});

  @override
  State<Yushinkan> createState() => _YushinkanState();
}

class _YushinkanState extends State<Yushinkan> {
  final AppwriteService _appwriteService = AppwriteService();

  @override
  void initState() {
    
    //Initializing Appwrite
    super.initState();
    _appwriteService.initAppwrite();
  }```
Drake
16 Nov, 2023, 01:35

What's the rest of the code?

nebukadnezar
16 Nov, 2023, 08:11
TypeScript
import 'package:appwrite/appwrite.dart';
import 'package:appwrite/models.dart';

class AppwriteService {
  static String projectId = '***';
  static String apiEndpoint = 'https://appwrite.samrahim.nl/v1';
  static String dojoDatabaseId = 'dojodb';
  static String noteCollectionId = 'notes';
  static Client appwriteClient = Client();
  static final Account _appwriteAccount = Account(appwriteClient);
  late Databases appwriteDatabase;

  AppwriteService._();

  static final AppwriteService _appwriteService = AppwriteService._();

  factory AppwriteService() => _appwriteService;

  // init the client
  void _initClient() {
    appwriteClient
        .setEndpoint(apiEndpoint)
        .setProject(projectId)
        .setSelfSigned(status: true);
  }

  // init the databases using client
  void _initDatabase(client) {
    appwriteDatabase = Databases(client);
  }

  // Initialize
  void initAppwrite() {
    _initClient();
    _initDatabase(appwriteClient);
  }

  Future<List<Document>> getNotes() async {
    DocumentList allNotes = await appwriteDatabase.listDocuments(
      databaseId: dojoDatabaseId,
      collectionId: noteCollectionId,
      queries: [
        Query.select([
          'subject',
          'description',
          'date',
          'id',
          //Permission is tijdelijk vanwege een bug in de SDK
          '\$permissions'
        ]),
        Query.orderDesc('date'),
      ],
    );
    return allNotes.documents;
  }

  void createNote(Map<dynamic, dynamic> noteData, String noteId) {
    try {
      appwriteDatabase.createDocument(
          databaseId: dojoDatabaseId,
          collectionId: noteCollectionId,
          documentId: noteId,
          data: noteData);
    } on AppwriteException catch (e) {
      print(e);
    }
  }

Here you go

Drake
17 Nov, 2023, 04:17

Do you have a valid certificate?

Maybe you can test making a http request to Google to confirm you have networking enabled

nebukadnezar
17 Nov, 2023, 10:55

Is that necessary? Because in runtime certain exceptions are handled by the Flutter framework and eventually still connects to the DB. The only difference is that sometimes, even though I see in the dashboard that the list of documents is updated, it still returns the previous state of the listDocuments. As you can see in the code here I print whatever listDocuments() returns.

Because it connects to the DB eventually I think we can rule out network permissions right?

TypeScript
Future<List<TrainingNote>> downloadTrainingNotes() async {
    const int maxRetries = 3;
    int retryCount = 0;

    while (retryCount < maxRetries) {
      try {
        List<Document> notesFromTheCloud = await _appwriteService
            .getNotes()
            .timeout(const Duration(seconds: 10));
        _trainingNotes.clear();
        for (Document note in notesFromTheCloud) {
          //For debug purposes
          print('The subject was: ${note.data['subject']}');
          TrainingNote trainingNote = TrainingNote.fromJsonToObject(note.data);
          _trainingNotes.add(trainingNote);
        }
        return _trainingNotes;
      } on TimeoutException catch (e) {
        print("Timeout bij het ophalen van notities: $e");
        retryCount++;
        print("Opnieuw proberen poging $retryCount...");
        Future.delayed(const Duration(seconds: 2));
      } catch (error) {
        print('Fout bij het ophalen van notities: $error');
        return <TrainingNote>[];
      }
    }

    print(
        "Maximale pogingen bereikt, kon notities niet ophalen na $maxRetries pogingen");
    return <TrainingNote>[];
  }```
nebukadnezar
17 Nov, 2023, 13:13

I might know whats going on. I think I should be using RealTime for this feature instead of async Futures in Dart. But then again, it shouldn't give an exception.

As you suggested I've manually put the permissions for internet but to no avail.

nebukadnezar
22 Nov, 2023, 11:39

Hi @Drake, I placed a print statement everytime the listDocument method gets executed. I noticed something strange happening. This is my code:

TypeScript
    DocumentList allNotes = await appwriteDatabase.listDocuments(
      databaseId: dojoDatabaseId,
      collectionId: noteCollectionId,
      queries: [
        Query.select([
          'subject',
          'description',
          'date',
          'id',
          //Temp because of a bug in the sdk
          '\$permissions'
        ]),
        Query.orderDesc('date'),
      ],
    );
    print(allNotes.documents.length);
    return allNotes.documents;
  }```
At the end you can see that I have a print statement which tells me this amount of documents in the DB. However I see in the DB that there are 6 documents. The print statement shows I got 5 documents. Is this an issue you've read somewhere before?
nebukadnezar
22 Nov, 2023, 16:30

Okay it's solved now. It was due to my programming skills honestly. The addNote/createNote method that uses the createDocument method of the SDK wasn't async. I've added the Future<void> and now everything is peachy. Leaving this here for other devs to read my silly mistake.

nebukadnezar
22 Nov, 2023, 16:31

[Solved] Socket exception

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more