android - 在 flutter 中显示 Firebase 中的数据

标签 android firebase dart flutter

我目前正面临 Flutter 和 Firebase 的问题。

我想显示我的 Firebase 数据库中的数据。

大部分代码来自 Fluttery 在 Tinder Cards 上的视频,我只是想学习如何在卡片上显示姓名、照片、年龄和传记。我现在只想做名称和描述。

我当前的代码:

class _ProfileCardState extends State<ProfileCard> {

   Widget _buildProfileSynopsis() {
    return new Positioned(
      left: 0.0,
      right: 0.0,
      bottom: 0.0,
      child: new Container(
        padding: const EdgeInsets.all(24.0),
        child: new Row(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            new Expanded(
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                   new StreamBuilder<Event>(
                      stream: FirebaseDatabase.instance
                      .reference()
                      .child('items')
                      .child('-LD2vzOCd54yEFNXJpGj')
                      .onValue,
                      builder: (BuildContext context, AsyncSnapshot<Event> event) {
                        if (!event.hasData)
                          return new Center(child: new Text('Loading...'));
                        Map<dynamic, dynamic> data = event.data.snapshot.value;
                      return new Text('${event.data.snapshot.value}', style: new TextStyle(
                        fontSize: 30.0)
                        );
                      },
                    ),
                    new StreamBuilder<Event>(
                      stream: FirebaseDatabase.instance
                      .reference()
                      .child('items')
                      .child('-LD2vzOCd54yEFNXJpGj')
                      .onValue,
                      builder: (BuildContext context, AsyncSnapshot<Event> event) {
                        if (!event.hasData)
                          return new Center(child: new Text('Loading...'));
                        Map<dynamic, dynamic> data = event.data.snapshot.value;
                      return new Text('-${event.data.snapshot.value}');
                      },
                    ),
                ],
              ),
            ),
            new Icon(
              Icons.info,
              color: Colors.black,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      decoration: new BoxDecoration(
        borderRadius: new BorderRadius.circular(10.0),
        boxShadow: [
          new BoxShadow(
            color: const Color(0x11000000),
            blurRadius: 5.0,
            spreadRadius: 2.0,
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: new BorderRadius.circular(10.0),
        child: new Material(
          child: new Stack(
            fit: StackFit.expand,
            children: <Widget>[
              _buildProfileSynopsis(),
            ],
          ),
        ),
      ),
    );
  }
class Males {
  String name, description;

  Males(this.name, this.description);
}
}

图片:

Importan screenshot

Image of my Database

正如您在我的 Firebase 的屏幕截图中看到的,每个人都有一个唯一的 key , 这使得很难引用单个数据。这是我的主要问题,因为我不知道如何将帐户 key 保存在字符串中,所以我可以做 .child(accountkey)。

所有的 youtube tuturials 都显示一个 ListView ,但它只是在卡片上的列表中显示数据,这没有用,因为每张卡片都会显示每个用户。

提前致谢,如果您有任何问题,请告诉我。我希望你能帮助:)

最佳答案

早上好

我的方法和你的不一样。我总是写一个类来从数据源获取数据,然后我在任何地方都使用它。我认为你是这个框架的新手,所以我会逐步解释

获取数据类是:

class GetItemsFromDb {
  static Future<List> getItems( ) async {
    Completer<List> completer = new Completer<List>();

    FirebaseDatabase.instance
        .reference()
        .child("males")
        .once()
        .then( (DataSnapshot snapshot) {
      //print(snapshot.value);
      List map = snapshot.value;
      completer.complete(map);
    } );

    return completer.future;
  }
}

正如你所说,你想要男性中的所有项目。 Firebase 数据库会给你一个 map 列表( map 是一本字典)。

我会再次重写你的男性对象

class Males {
  String names;
  String desc;


  // empty constructor 
  Males();

  // constructor for firebase databases 
  Males.fromMap(Map<String, dynamic> map){
    names = map["name"];
    desc  = map["description"];
  }

}

现在你把它放在你的 View 中

  List<Males> _males = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    GetItemsFromDb.getItems().then((list){
      print("Now the list is here");

      setState(() {
        for (int i=0; i < list.length; i++) {
          Map<String, dynamic> map = list[i];

          Males male = new Males.fromMap(map);
          _males.add(male);
        }
      });

    });
  }

现在您拥有来自 firebase 的完整列表及其数据,您可以将它们全部显示

关于android - 在 flutter 中显示 Firebase 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51410710/

相关文章:

java - 从 SeekBar 设置进度

ios - 用户遇到与 Firestore Pod 内部 grpc::ClientAsyncReaderWriter<grpc::ByteBuffer, grpc::ByteBuffer>::Finish 相关的崩溃

android - Firebase Android 离线性能

android - 如何在 Flutter 应用中播放 .mp3 文件?

flutter - 当前的 Dart SDK 版本是 2.10.4。如何将版本更改为高版本。?在测试版或开发 channel 中

android - DiffUtil 没有更新 RecyclerView

android - Flutter 缓存非常老的错误

android - 如果我递归调用 startActivityForResult() 会发生什么?

sql - 在 for 循环中等待 Future

android - 在通知点击时打开特定应用程序