我需要做一个 firebase 流而不是一个 Http Get

I need to do a firebase stream and not a Http Get

我正在尝试在 flutter 中使用 bloc 模式,但我遇到了一些问题,因为我需要实时获取数据,但是对于我拥有的 bloc,我只在更新应用程序时获取数据,因为 bloc 使用Http Get 并且我需要使用 Stream ,有人可以帮助我吗?

这就是集团所做的事情:

final response = await client.get("$url/Proyectos/-Lm78GugBsy29c0Zxziy.json");
    if (response.statusCode == 200) {
      return ProyectoModel.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load post');
    }

这就是我需要的:

StreamBuilder(
  stream:dataBaseRef.child("Proyectos").child("Lm78GugBsy29c0Zxziy").onValue,
  builder:(contex.snapshot){
    if(snapshot.hasData){
        return ProyectoModel.fromJson(snapshot.data.value);
      }
  },
);

创建一个新文件并将其命名为database.dart

database.dart

abstract class Database {
  Stream<ProyectoModel> countersStream();
}

class AppFirestore implements Database {
    static final String rootPath = 'Users';
    Stream<ProyectoModel> countersStream() {
        turn _DatabaseStream<Proyectos>(
            apiPath: rootPath,
            parser: _DatabaseCountersParser(),
        ).stream;
    };
}

class _DatabaseStream<T> {
  _DatabaseStream({String apiPath, DatabaseNodeParser<T> parser}) {
    FirebaseDatabase firebaseDatabase = FirebaseDatabase.instance;
    DatabaseReference databaseReference =
        firebaseDatabase.reference().child(apiPath);
    var eventStream = databaseReference.onValue;
    stream = eventStream.map((event) => parser.parse(event));
  }

  Stream<T> stream;
}

abstract class DatabaseNodeParser<T> {
  T parse(Event event);
}

class _DatabaseCountersParser implements DatabaseNodeParser<ProyectoModel> {
  ProyectoModel parse(Event event) {
    Map<dynamic, dynamic> values = event.snapshot.value;
    if (values != null) {
      Iterable<String> keys = values.keys.cast<String>();

      var model = keys
          .map((key) => ProyectoModel(id: int.parse(key), name: values["name"]))
          .toList();
      model.sort((lhs, rhs) => rhs.id.compareTo(lhs.id));
      return model;
    } else {
      return [];
    }
  }
}

然后在流生成器所在的 dart 文件中添加此代码。

var database = AppFirestore();
var stream = database.countersStream();

StreamBuilder(
    stream:stream,
    builder:(contex.snapshot){
        if(snapshot.hasData){
            return ProyectoModel.fromJson(snapshot.data.value);
        }
    },
);