0

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);
    }
  }
}

1 Answer 1

2
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');
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you refactor your code? The function .execute()_ and the corresponding response.data() and .error() are deprecated/not allowed.
Thanks. How can I use this?
You can call this method in FutureBuilder and handle your Ui there.
I have succeeding issue/question here . I used it in a FutureBuilder and the list of questions show after a brief error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.