如何从Firebase实时数据库中获取数据到Flutter中的列表中? [英] How to get data from Firebase Realtime Database into list in Flutter?

查看:83
本文介绍了如何从Firebase实时数据库中获取数据到Flutter中的列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用模型从Firebase实时数据库中将数据检索到Flutter中的列表中.执行此操作时,我的列表将返回null.我还阅读了其他有关在Flutter上使用Firebase的文章,但没有找到明确的答案.这是我目前的方法(该对象称为需求",我正在尝试检索并显示需求列表):

I am trying to retrieve data from Firebase Realtime Database into a list in Flutter using a model. My list is returning as null when I do this. I have read several other posts about using Firebase with Flutter but have not found a clear answer. Here is my current approach (the object is called a 'need', and I am trying to retrieve and display a list of needs):

型号:

import 'package:firebase_database/firebase_database.dart';

class Need {
  final String id;
  final String imageUrl;
  final String caption;
  final String title;

  Need({
    this.id,
    this.imageUrl,
    this.caption,
    this.title,
  });

  Need.fromSnapshot(DataSnapshot snapshot) :
    id = snapshot.key,
    imageUrl = snapshot.value["imageUrl"],
    caption = snapshot.value["caption"],
    title = snapshot.value["postTitle"];

  toJson() {
    return {
      "imageUrl": imageUrl,
      "caption": caption,
      "title": title,
    };
  }
}

具有Firebase查询的数据库服务:

Database service with Firebase query:

import 'package:firebase_database/firebase_database.dart';
import 'package:Given_Flutter/models/need_model.dart';

class DatabaseService {

  static Future<List<Need>> getNeeds() async {
    Query needsSnapshot = await FirebaseDatabase.instance
      .reference()
      .child("needs-posts")
      .orderByKey();

    print(needsSnapshot); // to debug and see if data is returned

    List<Need> needs;

    Map<dynamic, dynamic> values = needsSnapshot.data.value;
    values.forEach((key, values) {
      needs.add(values);
    });

    return needs;
  }
}

ListView:

import 'package:flutter/material.dart';
import 'package:Given_Flutter/models/need_model.dart';
import 'package:Given_Flutter/services/database_service.dart';
import 'package:Given_Flutter/need_view.dart';

class Needs extends StatefulWidget {
  static final String id = 'needs_screen';

  @override
  _NeedsState createState() => _NeedsState();
}

class _NeedsState extends State<Needs> {
  List<Need> _needs = [];

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

  _setupNeeds() async {
    List<Need> needs = await DatabaseService.getNeeds();
    setState(() {
      _needs = needs;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: () => _setupNeeds(),
        child: ListView.builder(
          itemCount: _needs.length,
          itemBuilder: (BuildContext context, int index) {
            Need need = _needs[index];
            return NeedView(
              need: need,
            );
          }
        )
      )
    );
  }
}

Firebase实时数据库结构:

Firebase Realtime Database structure:

Firebase示例

我在做什么错了?

推荐答案

地图<动态,动态>值= needsSnapshot.data.value; 是错误的.

值是数据,因此只需使用 Map< dynamic,dynamic>值= needsSnapshot.value;

Value is the data, so just use Map<dynamic, dynamic> values = needsSnapshot.value;

您添加到列表的对象也不会转换.

Also the object your appending to to the List is not converted..

// wrong
Map<dynamic, dynamic> values = needsSnapshot.data.value;
    values.forEach((key, values) {
      needs.add(values);
    });

// correct
Map<dynamic, dynamic> values = needsSnapshot.data.value;
    values.forEach((key, values) {
      needs.add(Need.fromSnapshot(values));
    });

还有一件事,我对此不是100%肯定,但是如果我将List声明为null,则在向其添加值时会遇到问题,因此我始终将as声明为空列表.因此,代替了 List< Need>需求; 我会使用 List< Need>需求= [];

One more thing, I'm not 100% sure on this, but if I declare my List as null I have problems when adding value to it, so I always declare the as empty lists.. So instead of List<Need> needs; I'd use List<Need> needs = [];

希望您已经解决了这个问题,但是如果没有解决的话.我只是遇到了同样的问题.干杯

Hope you solved it already but if not this should work. I just went through the same problem.. Cheers

这篇关于如何从Firebase实时数据库中获取数据到Flutter中的列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆