fluttersupabasesupabase-flutter

Creating and using a Model and Repository in Flutter issue


As a newbie in Flutter, I am trying to create a class and its corresponding repository for a Question type. I found a sample pattern here but it seems deprecated as shown below:

class Note {
  final String id;
  final String title;
  final String content;

  Note({
    required this.id,
    required this.title,
    required this.content,
  });
}
import 'package:supabase_flutter/supabase_flutter.dart';

class NoteRepository {
  final String tableName = 'notes';

  Future<List<Note>> getNotes() async {
    final response = await Supabase.client.from(tableName).select().execute();

    if (response.error == null) {
      final notes = (response.data as List)
          .map((data) => Note(
                id: data['id'].toString(),
                title: data['title'].toString(),
                content: data['content'].toString(),
              ))
          .toList();

      return notes;
    } else {
      throw Exception('Failed to retrieve notes: ${response.error!.message}');
    }
  }

  Future<void> addNote(Note note) async {
    final response = await Supabase.client.from(tableName).upsert([
      {
        'id': note.id,
        'title': note.title,
        'content': note.content,
      }
    ]).execute();

    if (response.error != null) {
      throw Exception('Failed to add note: ${response.error!.message}');
    }
  }
  ...

I have used the .fromJson() template in some codes which I find it cleaner and I need to return a List of Question in the getQuestion function in the repository. How could I map the result from Question.fromJson() to form the List of questions?

Here is my current model:

class Question {
  final int id;
  final String questionText;
  final String? questionId;
  final int mainCategoryId;
  final int? subCategoryId;

  Question(
      {required this.id,
      required this.questionText,
      this.questionId,
      required this.mainCategoryId,
      this.subCategoryId});

  Question.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        questionText = json['question_text'],
        questionId = json['question_id'],
        mainCategoryId = json['main_category_id'],
        subCategoryId = json['sub_category_id'];
}

How can I fix my Question Repository to return the List of Questions? What should be the correct syntax? Thank you in advance!

class QuestionRepository {
  final supabase = Supabase.instance.client;

  Future<List<Question>> getQuestions() {
    try {
      final response = supabase.from('questions').select();
      // How could I fix the mapping here?
      
         questions = (response as List).map((e) => Question( ...  )

      //
    } catch (error) {
      throw Exception(error);
    }
  }
}

Solution

  • Future<List<Question>> getQuestions() async {
      try {
        final response = await supabase.from('questions').select();
    
        if (response.isNotEmpty) {
          final questions = response.map((data) => Question.fromJson(data))
              .toList();
    
          return questions;
        } else {
          throw Exception('Failed to fetch questions!!');
        }
      } catch (error) {
        throw Exception('Error fetching questions: $error');
      }
    }