Skip to content

Instantly share code, notes, and snippets.

@AnthonyDS
Last active January 25, 2023 06:45
Show Gist options
  • Save AnthonyDS/13b209f71b0e7572147697f2f6f48091 to your computer and use it in GitHub Desktop.
Save AnthonyDS/13b209f71b0e7572147697f2f6f48091 to your computer and use it in GitHub Desktop.
Flutter StreamController

Flutter StreamController

Created with <3 with dartpad.dev.

import 'package:flutter/material.dart';
import 'dart:async';
void main() {
///
/// Example 1
///
// final myStream = NumberCreator().stream;
// final subscription = myStream.listen(
// (data) => print('s: $data'),
// );
///
/// Example 2
///
// final myStream = NumberCreator()
// .stream
// .asBroadcastStream();
// final subscription1 = myStream.listen(
// (data) => print('s1: $data'),
// );
// final subscription2 = myStream.listen(
// (data) => print('s2: $data'),
// );
///
/// Example 3
// ///
// final myStream = NumberCreator().stream;
// final subscription = myStream.listen(
// (data) => print('s: $data'),
// onError: (err) => print('Error!'),
// cancelOnError: false,
// onDone: () => print('Done'),
// );
// Subscription:
// - subscription.pause();
// - subscription.resume();
// - subscription.cancel();
///
/// Example 4
///
// final myStream = NumberCreator()
// .stream
// .where((i) => i % 2 == 0)
// .map((i) => '${i + 1}')
// .listen(print); // Без подписчиков myStream.listen
runApp(
MaterialApp(
home: MyWidget(),
),
);
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
///
/// Example 1-4
///
// child: Text('Text'),
///
/// Example 5
///
// child: FutureBuilder<String>(
// future: _fetchNetworkData(),
// builder: (context, snapshot) {
// //
// },
// ),
///
/// Example 6
///
child: StreamBuilder<String>(
stream: NumberCreator().stream
.map((i) => '${i + 1}'),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if(snapshot.connectionState == ConnectionState.waiting) {
return const Text('No data yet.');
} else if(snapshot.connectionState == ConnectionState.done) {
return const Text('Done');
} else if(snapshot.hasError) {
return const Text('Error!', style: TextStyle(color: Colors.red));
} else {
return Text(snapshot.data ?? '');
}
},
),
),
);
}
}
class NumberCreator {
final _controller = StreamController<int>();
int _count = 0;
NumberCreator() {
// Увеличиваем счётчик на 1 каждую секунду.
Timer.periodic(const Duration(seconds: 1), (Timer timer) {
// Выполняем увеличение счётчика на 1 в течение 5 секунд.
// Timer(const Duration(seconds: 5), () {
_controller.sink.add(_count);
_count++;
if(_count == 3) {
_controller.addError(Exception('Ta-da!'));
}
if(_count >= 5) {
timer.cancel();
}
},
);
}
Stream<int> get stream => _controller.stream;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment