flutter firebase_database加入两个节点

时间:2017-05-25 17:00:21

标签: firebase plugins firebase-realtime-database dart flutter

通常,您可以在javascript中使用map函数来更新返回的数据。我似乎无法在Dart Streams中找到允许这种方法的方法。

实施例 https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html

var fb = new Firebase("https://examples-sql-queries.firebaseio.com/");
fb.child('user/123').once('value', function(userSnap) {
   fb.child('media/123').once('value', function(mediaSnap) {
       // extend function: https://gist.github.com/katowulf/6598238
       console.log( extend({}, userSnap.val(), mediaSnap.val()) );
   });
});

我正在尝试使用flutter firebase_database。

  var _fireFollower =FirebaseDatabase.instance.reference()
      .child('followers/' + auth.currentUser.uid);
  _fireFollower.onValue.map((snap){
    print(snap.snapshot.key);
  });

然而,map函数永远不会被调用,因此当从Firebase获取时,我无法加入任何其他数据。

此外,我尝试使用的是FirebaseAnimatedList,如果我不做地图,如何传递查询?

new FirebaseAnimatedList(
query: _fireFollower,
  sort: (a, b) => b.key.compareTo(a.key),
  padding: new EdgeInsets.all(8.0),
  reverse: false,
  itemBuilder: (_, DataSnapshot snapshot,
    Animation<double> animation) {
    return new Activity(
     snapshot: snapshot, animation: animation);
    },
    ),

2 个答案:

答案 0 :(得分:0)

在Flutter中,DatabaseReference.onValueStream,因此您必须在其上拨打Stream.listen并在听完后取消StreamSubscription。如果您只想获得一个值事件,则应该调用once()来获取表示快照值的Future。完成后,您将获得快照。

Future.wait([fb.child('media/123').once(), fb.child('user/123').once()])
  .then((snapshots) => print("Snapshots are ${snapshots[0]} ${snapshots[1]}"));

如果您在async函数中执行此功能,则可以更简单,因为您只需调用await即可获得once()的结果:

print("Snapshots are ${await ref1.once()} ${await ref2.once()}");

答案 1 :(得分:0)

我认为这是@ collin-jackson建议的解决方案,这是我的代码......

 return new Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    new Flexible(
                      child: new FirebaseAnimatedList(
                        query: FirebaseDatabase.instance
                                .reference()
                                .child('followers/${auth.currentUser.uid}'),
                        sort: (a, b) => b.key.compareTo(a.key),
                        padding: new EdgeInsets.all(8.0),
                        reverse: false,
                        itemBuilder: (_, DataSnapshot followerSnap,
                            Animation<double> animation) {
                          return new FutureBuilder<DataSnapshot>(
                            future: FirebaseDatabase.instance
                                .reference()
                                .child('users/${followerSnap.key}')
                                .once(),
                            builder: (BuildContext context,
                                AsyncSnapshot<DataSnapshot> userSnap) {
                              switch (userSnap.connectionState) {
                                case ConnectionState.none:
                                  return new Text('Loading...');
                                case ConnectionState.waiting:
                                  return new Text('Awaiting result...');
                                default:
                                  if (userSnap.hasError)
                                    return new Text(
                                        'Error: ${userSnap.error}');
                                  else
                                    return new User(snapshot: userSnap.data, animation: animation);
                              }
                            },
                          );
                        },
                      ),
                    ),
                  ]);

用户类

@override
class User extends StatelessWidget {
  User({this.snapshot, this.animation});
  final DataSnapshot snapshot;
  final Animation animation;

  Widget build(BuildContext context) {

    return new SizeTransition(
      sizeFactor: new CurvedAnimation(parent: animation, curve: Curves.easeOut),
      axisAlignment: 0.0,
      child: new Container(
        margin: const EdgeInsets.symmetric(vertical: 10.0),
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Container(
              margin: const EdgeInsets.only(right: 16.0),
              child: snapshot.value['photoURl'] == null
                  ? new CircleAvatar()
                  : new CircleAvatar(
                backgroundImage: new NetworkImage(snapshot.value['photoURl']),
              ),
            ),
            new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                new Text(snapshot.value['displayName'],
                    style: Theme.of(context).textTheme.subhead),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Followers, referencing Users.