Создание и использование модели и репозитория в проблеме Flutter

Будучи новичком во Flutter, я пытаюсь создать класс и соответствующий ему репозиторий для типа вопроса. Я нашел образец шаблона здесь, но он кажется устаревшим, как показано ниже:

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

Я использовал шаблон .fromJson() в некоторых кодах, которые кажутся мне более понятными, и мне нужно вернуть список вопросов в функцию getQuestion в репозитории. Как я могу сопоставить результат Вопроса.fromJson(), чтобы сформировать список вопросов?

Вот моя текущая модель:

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'];
}

Как я могу исправить свой репозиторий вопросов, чтобы он возвращал список вопросов? Каким должен быть правильный синтаксис? Заранее спасибо!

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

82
1

Ответ:

Решено
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');
  }
}