颤振|如何从 Firestore 获取对象列表?

时间:2021-02-19 12:46:22

标签: firebase flutter google-cloud-firestore

这是我的问题对象:

export interface ApiState<T> {
    data: null|T;
    error: null|AxiosError;
}



export const request = async<T>( config: AxiosRequestConfig ) => {
    const state: ApiState<T> = {
        data: null,
        error: null
    }
    try {
        const { data } = await http.request<T>(config);
        
        // How can I cast the state.data to another 'type'?
        state.data = data as T; // how can I make the intellisense recognize the passed <T> type?
    } catch(e) {
        state.error = e;
    }
    return state;
}



export const user = async () => {
    const state = await request<ApiUser>({ url: '/api/user', method: 'GET' });

    // this is seen as unknown
    // How can I make this of type ApiUser?
    console.log(state.data)
}

我想像这样从 Firestore 获取问题列表:

class Question {
  String text;
  String correctAnswer;
  bool answer;

  Question(String q, bool a, String ca) {
    text = q;
    answer = a;
    correctAnswer = ca;
  }
}

Firestore 看起来像这样: firestore

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

你可以像这样从firestore获取数据

void _onPressed() {
  firestoreInstance.collection("Questiions").get().then((querySnapshot) {
    querySnapshot.docs.forEach((result) {
      print(result.data());
    });
  });
}

有关更多详细信息,您可以参考此 https://medium.com/firebase-tips-tricks/how-to-use-cloud-firestore-in-flutter-9ea80593ca40

答案 1 :(得分:1)

从 Cloud Firestore 检索问题并转换为列表:

  Future<List<Question>> fetchQuestions(String userId) async {
    final questions = new List<Question>();
    final doc = await FirebaseFirestore.instance.collection('Questions').doc(userId).get();
    final questionsTmp = doc.data().questions;
    questionsTmp.forEach((questionTmp) {
      questions.add(Question.fromMap(questionTmp));
    });
    return questions;
  }

将 fromMap 方法添加到 Question 类:

class Question {
  String text;
  String correctAnswer;
  bool answer;

  Question(String q, bool a, String ca) {
    text = q;
    answer = a;
    correctAnswer = ca;
  }

  static Question fromMap(Map<String, dynamic> map) {
    return Question(
      map['text'],
      map['answer'],
      map['correctAnswer'].ToString() == 'true'
    );
  }
}