Reputation: 394
i'm trying to use bloc pattern in flutter but i'm getting some issues because i need to get the data in realtime but with the bloc that i have i only get the data when update the app because bloc use Http Get and i need to use Stream , can any one help me ?
this is what the bloc do :
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');
}
and this is what i need :
StreamBuilder(
stream:dataBaseRef.child("Proyectos").child("Lm78GugBsy29c0Zxziy").onValue,
builder:(contex.snapshot){
if(snapshot.hasData){
return ProyectoModel.fromJson(snapshot.data.value);
}
},
);
Upvotes: 1
Views: 165
Reputation: 1343
create a new file and name it 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 [];
}
}
}
then in your dart file where stream builder resides add this code.
var database = AppFirestore();
var stream = database.countersStream();
StreamBuilder(
stream:stream,
builder:(contex.snapshot){
if(snapshot.hasData){
return ProyectoModel.fromJson(snapshot.data.value);
}
},
);
Upvotes: 2