Skip to content

Instantly share code, notes, and snippets.

@OmarYehiaDev
Created May 30, 2022 23:54
Show Gist options
  • Save OmarYehiaDev/58a51fe248369c5b39ce20542794df50 to your computer and use it in GitHub Desktop.
Save OmarYehiaDev/58a51fe248369c5b39ce20542794df50 to your computer and use it in GitHub Desktop.
StreamBuilder Example
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Stream<int> generateNumbers = (() async* {
await Future<void>.delayed(const Duration(seconds: 2));
for (int i = 1; i <= 500; i++) {
await Future<void>.delayed(const Duration(seconds: 5));
yield i;
}
})();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("title"),
),
body: Center(
child: StreamBuilder<int>(
stream: generateNumbers,
initialData: 0,
builder: (
BuildContext context,
AsyncSnapshot<int> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
Visibility(
visible: snapshot.hasData,
child: Text(
snapshot.data.toString(),
style: const TextStyle(color: Colors.black, fontSize: 24),
),
),
],
);
} else if (snapshot.connectionState == ConnectionState.active ||
snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(snapshot.data.toString(),
style: const TextStyle(color: Colors.teal, fontSize: 36));
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment