【问题标题】:How can I retrieve data from Firestore to my list如何将数据从 Firestore 检索到我的列表
【发布时间】:2020-09-09 01:25:02
【问题描述】:
class Profile {

  final List<String> photos;
  final String name;
  ......

  Profile({
    this.photos,
    this.name,
    ......
  });

}

final List<Profile> demoProfiles = [
  Profile (
    photos: [
      "https:...",

    ],
    name: "Fatih",
    age: 22,
    distance: 4,
    education: "Hacettepe University"
  ),
  Profile (
    photos: [
       "https:...",
       "https:...",

    ],
    name: "Elysium",
    age: 23,
    distance: 2,
    bio: "Test bio"
  )
];

如何从 Firestore 检索数据,然后更新我的 List demoProfiles 并在我的 main_controller.dart 中使用它?我真的是 Flutter 新手,谁能帮帮我?谢谢。

final MatchEngine matchEngine = MatchEngine (
    matches:demoProfiles.map((Profile profile) => Match(profile: profile)).toList()
  );

【问题讨论】:

  • 我试图将我的 main_controller.dart 更改为上面的屏幕截图,但它返回了错误:type 'Future' is not a subtype of type 'List
  • 你能收到来自firebase的数据吗?
  • 是的,我试着把数据打印出来,没关系
  • 那么现在有什么问题?
  • 它返回了一个错误:“Future>”类型的值不能分配给“List”类型的变量。如果我在其他页面之间导航和主控制器,它返回错误:NoSuchMethodError: The method 'map' was called on null

标签: firebase flutter dart google-cloud-firestore future


【解决方案1】:

你可以这样做

List<Profile> demoProfiles = [];

@override
void initState() {
  super.initState();
  loadDataMethod();
}

void loadDataMethod() async {
  demoProfiles = await fetchData();
  setState(() {});
}


Future<List<Profile>> fetchData() async {
  List<Profile> list;
  // Fetch Data Logic
  return list;
}

或者像这样

List<Profile> demoProfiles = fetchData() as List<Profile>;

【讨论】:

  • 返回错误:List demoProfiles package:flutter_chat_demo/src/scenes/in/main_controller.dart 在初始化器中只能访问静态成员。
  • 抱歉回复晚了,我更新了错误和匹配引擎。请看一下
  • @ZivCheung 删除静态关键字
【解决方案2】:

你能像下面这样试试吗?

Future<Profile> fetchData() async {...}

【讨论】:

  • 好吧,我有一个解决方案给你..可能不是一种有效的方法......但是..希望它会起作用,很可能,..这是我的解决方案..只需声明 demoProfiles作为var..like this..var demoProfiles = fetch data();,如果它对你有用,请回复..
  • 你能不能试试list.add(doc.data)而不是new Profile(...) 如果它不适合你在.documents; 之后尝试list = querySnapshot.documents而不是使用forEach方法。
猜你喜欢
  • 2020-12-26
  • 2021-08-01
  • 2021-05-05
  • 2020-12-10
  • 1970-01-01
  • 2023-03-29
  • 2021-10-26
  • 2021-07-09
  • 2021-02-16
相关资源
最近更新 更多