What is the use of yield in flutter proviide me with some real world example ?
#flutter
Answer
yield in Flutter/Dart
yield enables creating generator functions that return values one at a time.
Basic yield
dartStream<int> countUp() async* { for (int i = 1; i <= 5; i++) { await Future.delayed(Duration(seconds: 1)); yield i; } } void main() { countUp().listen((value) => print(value)); // Prints: 1, 2, 3, 4, 5 (with 1 second delays) }
Real-world: Data Streaming
dartStream<User> fetchUsersStream() async* { final response = await http.get(Uri.parse('/api/users')); final users = jsonDecode(response.body) as List; for (var userData in users) { yield User.fromJson(userData); await Future.delayed(Duration(milliseconds: 100)); } } // Usage in UI StreamBuilder<User>( stream: fetchUsersStream(), builder: (context, snapshot) { if (snapshot.hasData) return Text(snapshot.data!.name); if (snapshot.hasError) return Text('Error'); return CircularProgressIndicator(); }, )
yield with Pagination
dartStream<List<Product>> fetchProductsStream(int pageSize) async* { int page = 0; while (true) { final products = await fetchPage(page, pageSize); if (products.isEmpty) break; yield products; page++; } }
Use: Streaming data over time, pagination, real-time updates.