如何实时显示Firebase列表? [英] How to display a Firebase list in REAL TIME?

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

问题描述

我有一个TODO List函数(警报),但是我觉得我没有充分利用Firebase的实时功能.

I have a TODO List function (Alarmas), but I feel I'm not taking advantage of Firebase's Realtime features enough.

窗口小部件很好地显示了列表,但是当有人从另一部手机发出新任务时,我无法自动显示它,但是我必须通过单击"TODO button"再次调用构建.在BottomNavigationBar中.

The Widget displays the list very well, however when someone puts a new task from another cell phone, I am not being able to show it automatically, but I must call the build again by clicking on the "TODO button" in the BottomNavigationBar.

有没有一种方法可以自动显示新任务而无需执行任何操作?

Is there a way that the new tasks are automatically displayed without doing anything?

我正在使用流来获取列表...

I'm using streams to get the list...

@override
  Widget build(BuildContext context) {
    alarmaBloc.cargarAlarmas();

///---Scaffold and others

return StreamBuilder(
          stream: alarmaBloc.alarmasStream,
          builder: (BuildContext context, AsyncSnapshot<List<AlarmaModel>> snapshot){
            if (snapshot.hasData) {
              final tareasList = snapshot.data;
              if (tareasList.length == 0) return _imagenInicial(context);
            
              return ListView(

                children: [
                  for (var itemPendiente in tareasList)
                    _crearItem(context, alarmaBloc, itemPendiente),
                  //more widgets
                  ],
              );
            } else if (snapshot.hasError) {
              return Text(snapshot.error.toString());
            } 
              return Center (child: Image(image: AssetImage('Preloader.gif'), height: 200.0,));
          },
      ),

而且,我以这种方式读取Firebase数据...

And, I read the Firebase Data in this way...

Future<List<AlarmaModel>> cargarAlarmas() async {

  final List<AlarmaModel> alarmaList = new List(); 

  Query resp = db.child('alarmas');

  resp.onChildAdded.forEach((element) {
        
        final temp = AlarmaModel.fromJson(Map<String,dynamic>.from(element.snapshot.value));
        temp.idAlarma = element.snapshot.key;
        alarmaList.add(temp);    // element.snapshot.value.
  });

  await resp.once().then((snapshot) {
    print("Total list was loaded - ${alarmaList.length}");
  }); //I'm using this await to be sure that the full list was loaded, so I can order and process it later

      return alarmaList;

}

如何从Firebase中以"true"显示列表?实时吗?

How can I display a List from Firebase in "true" Real Time?

推荐答案

要正确管理异步加载的数据的状态,您应该:

To properly manage the state of asynchronously loaded data, you should:

  1. 开始加载/监听 initState()
  2. 中的数据
  3. 在收到数据或更新数据时将数据设置为状态(使用 setState()).
  4. 然后从 build 方法中的状态呈现它.
  1. Start loading/listening to the data in initState()
  2. Set the data into the state (with setState()) when you receive it or it is updated.
  3. Then render it from the state in the build method.

因此,在您的代码中,类似:

So in your code that'd be something like:

final List<AlarmaModel> alarmaList = new List();  // this is now a field in the `State` object

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

  Query resp = db.child('alarmas');

  resp.onChildAdded.forEach((element) {
        final temp = AlarmaModel.fromJson(Map<String,dynamic>.from(element.snapshot.value));
        temp.idAlarma = element.snapshot.key;
        alarmaList.add(temp);

        setState(() {
          alarmaList = alarmaList;
        })
  });

}
@override
  Widget build(BuildContext context) {
    ///---Scaffold and others

    return StreamBuilder(
          stream: alarmaBloc.alarmasStream,
          builder: (BuildContext context, AsyncSnapshot<List<AlarmaModel>> snapshot){
            if (snapshot.hasData) {
              final tareasList = snapshot.data;  

如果您只想在从数据库中获得完整更新后就重新绘制,则可以将对 setState()的调用放在 value 侦听器中,在其中使用 onValue 而不是 once(),因为您还想捕获更新.

If you only want to repaint once you've gotten a complete update from the database, you can put the call to setState() in a value listener, just use onValue in that instead of once(), as you also want to catch the updates.

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

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