Skip to content

Instantly share code, notes, and snippets.

@Luckey-Elijah
Created January 22, 2021 20:07
Show Gist options
  • Save Luckey-Elijah/651efae7457105f49e7766e9559c2652 to your computer and use it in GitHub Desktop.
Save Luckey-Elijah/651efae7457105f49e7766e9559c2652 to your computer and use it in GitHub Desktop.
Wrapping stream and working with data.
void main() async {
// This is where you would use a StreamBuilder rather than this use.
await for (var value in getData()) {
print(value);
}
print('Done!');
/*
* return StreamBuilder(
* stream: getData(),
* builder: (contaxt, snapshot) => YourWidget(snapshot.data);
* );
* */
}
// This is *your* Stream function.
Stream<List> getData() async* {
var list = [];
// Make sure the stream you are wrapping is invokable.
await for (var data in mockRemoteData()) {
list.add(Data.fromMap(data));
yield list;
}
}
// Ignore the implmentation, just imagine you are recieving data from a network
// and it just timeouts at some point.
Stream<Map> mockRemoteData() async* {
const sampleData = [
{'icon': 'delte', 'nome': 'Junior'},
{'icon': 'add', 'nome': 'Televisao'},
{'icon': 'bulb', 'nome': 'Batata'}
];
for (int i = 0; i < sampleData.length; i++) {
await Future.delayed(const Duration(seconds: 1));
yield sampleData[i];
}
}
class Data {
var icon;
var nome;
Data(this.icon, this.nome);
factory Data.fromMap(Map<String, dynamic> map)=> Data(map['icon'], map['nome']);
@override
toString() => 'Data(icon: $icon, nome: $nome)';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment