Skip to Content

Streams trong Dart

🎯 Mục tiêu: Streams - async sequence of values.


💡 Tạo Stream

// Từ iterable Stream<int> numbers = Stream.fromIterable([1, 2, 3, 4, 5]); // Periodic Stream<int> periodic = Stream.periodic( Duration(seconds: 1), (count) => count ); // Async* generator Stream<int> countStream() async* { for (int i = 0; i < 5; i++) { await Future.delayed(Duration(seconds: 1)); yield i; } }

📝 Listen

var stream = countStream(); stream.listen( (data) => print(data), onError: (error) => print("Error: $error"), onDone: () => print("Done"), );

🔧 await for

await for (var value in countStream()) { print(value); }

📱 Trong Flutter - StreamBuilder

StreamBuilder<int>( stream: countStream(), builder: (context, snapshot) { if (snapshot.hasData) { return Text('Count: ${snapshot.data}'); } return CircularProgressIndicator(); }, );

✅ Checklist

  • Stream cho multiple async values
  • async*yield
  • listen hoặc await for

Last updated on