Home > Enterprise >  Fetch data from Firestore instead of sample data, type List<dynamic>
Fetch data from Firestore instead of sample data, type List<dynamic>

Time:03-15

Question Model class for quiz. How to add firestore instead of sample data.

class Question {
  final int id, answer;
  final String question;
  final List<String> options;

  Question({required this.id, required this.question, required this.answer, required this.options});
}

List sample_data = [
  {
    "id": 1,
    "question": "1. Easy Question, Correct Ans : 2",
    "options": ['ESFJ and ENFJ', 'ISFJ and INFJ'],
    "answer_index": 1,
  },
  {
    "id": 2,
    "question": "2. Medium Question, Correct Ans : 1",
    "options": ['ESFJ and ENFJ', 'ISFJ and INFJ'],
    "answer_index": 0,
  },
];

//I have used getxcontroller Here is the getxcontroller code.

List<Question> _questions = sample_data
      .map(
        (question) => Question(
            id: question['id'],
            question: question['question'],
            options: question['options'],
            answer: question['answer_index']),
      )
      .toList();

  List<Question> get questions => this._questions;

CodePudding user response:

See FlutterFire documentation for more. there are many examples and todo app on GitHub to show how connect with firebase.

CodePudding user response:

I have tried this code to fetch data from firestore and tried to keep in sample_data

Stream<List<dynamic>> streamDemo() {
  return FirebaseFirestore.instance
      .collection('questions')
      .doc()
      .snapshots()
      .map((ds) {
    var mapData = ds.data();
    sample_data = mapData![
    Question(
        id: ds['id'],
        question: ds['question'],
        options: ds['options'],
        answer: ds['answer_index'])
    ];
    return sample_data;
  });
}
  • Related