Skip to content

Instantly share code, notes, and snippets.

@AdelDaniel
Last active May 11, 2021 14:40
Show Gist options
  • Select an option

  • Save AdelDaniel/f8606c85bf28c08b46074f6a8d82e34e to your computer and use it in GitHub Desktop.

Select an option

Save AdelDaniel/f8606c85bf28c08b46074f6a8d82e34e to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
/*
///******* Stream Controller start from video 6 *********///
1- used to send data to that Stream
* 2- This controller allows sending data, error and done events on its stream.
* 3- this class can be used to create a simple stream that others can listen on, and to push events to that stream.
*/
StreamController<String> sc = StreamController<String>();
StreamController<String> scb = StreamController<String>.broadcast();// to use multi Listen functions
void main() {
sc.stream.listen((String data)=>print(data)); // listen to data comes form Stream
// sc.stream.listen((String data)=>print(data)); // will not Work notBroadcast
sc.sink.add("good"); //add data To stream
scb.stream.listen((String data)=>print('$data 1'));
scb.stream.listen((String data)=>print('$data 2'));
scb.stream.listen((String data)=>print('$data 3'));
scb.sink.add("this is broadcast");
scb.close();
sc.close();
/// ************** App in video 7 the StreamBuilder ************* ///
runApp(App());
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Home(),
);
}
}
class HomeModel {
final StreamController<int> _numbersController = StreamController<int>.broadcast();
Stream<int> get outNumbers => _numbersController.stream;
Sink<int> get inNumbers => _numbersController.sink;
void dispose() {
_numbersController.close();
}
}
class Home extends StatelessWidget {
final model = HomeModel();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Widget1(model),
Widget2(model),
],
)
);
}
}
class Widget1 extends StatelessWidget {
final HomeModel _model;
Widget1(this._model);
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: _model.outNumbers,
builder: (context, snapshot) {
return Text(snapshot.hasData ? snapshot.data.toString() : 'no data here', style: TextStyle(fontSize: 50),);
},
);
}
}
class Widget2 extends StatelessWidget {
final HomeModel _model;
Widget2(this._model);
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
_model.inNumbers.add(Random().nextInt(20000));
},
child: Text('press me'),
);
}
}
import 'dart:async' ;
listen(){
//***** listen *****//
int sum = 0 ;
getNum().
listen((int num){
print(num);
sum+=num;
},
cancelOnError: false,
onDone: ()=>print("sum = $sum")
).onError( (e)=> print("error i%3==0") );
}
waitFor() async{
//***** await For *****//
//in await for >> used with the Streams
// waits until the loop finished and getNum() == Done
// then go to the next line
//not very useful because no onError Handling
int sum2=10;
await for(int num in getNum()){
print(num);
sum2+=num;
}
print(sum2);
}
isEmpty() async {
//***** isEmpty *****//
// if there is only one piece of data reterend it is print not empty
if (await getNum().isEmpty)
print('yes empty');
else
print('no not empty');
}
any() async{
print( await getNum().any((int n)=> n==4));
}
void contains() async {
if (await getNum().contains(7)) {
print('there is a number equal to 7');
} else {
print('there is not a number equal to 7');
}
}
void join() async {
print(await getNum().join(', '));
}
skipAndTake(){
//***** Skip && Take *****//
getNum().skip(2).listen((data)=>print(data)); //skip first 2 yields
getNum().take(2).listen((data)=>print(data)); //take only first 2 yields
}
skipAndTakeWhile(){
// ***** Skip While *****//
// while the codation is true >> Skip the num (Skip while True)
// if it become false then all the coming nums >> will not done by test
getNum().skipWhile((int num){
return num == 2 ? true:false ;
}).listen((data){
print(data);
}) ;
/// ***** take While *****//
//while the codation is true >> Take the num >> (take while True)
}
void where() {
getNum()
.where((item) => item % 2 == 0)
.listen((data) {
print(data);
});
}
void distinct() {
// if yield return same value one after the other it will ingnore all //the next
///look at the [getNumbersDuplicates() mehtod] and edit it to understand
getNumbersDuplicates()
.distinct()
.listen((data) {
print(data);
});
}
void mix() {
getNumbersDuplicates()
.distinct()
.map((item) => item * 10)
.where((item) => item != 20)
.listen((data) {
print(data);
});
}
transform(){
getNum().transform<int>(StreamTransformer<int,String>.fromHandlers());
}
void main() async {
/* Complte the next Stream Methods From Next link
https://www.youtube.com/watch?v=zH6arYHP25I&list=PL_Wj0DgxTlJc8E3ulwdekyVI4Wc819azh&index=3
*/
/* No Error check in this methods
* no returning Streams also
* easy to understansd */
{
// print(await getNum().first);
// print(await getNum().last);
// print(await getNum().length);
// print(await getNum().single);
// print(await getNum().elementAt(10));
// print(await getNum().firstWhere((i) => i > 12));
// print(await getNum().lastWhere((i) => i > 1));
// print(await getNum().singleWhere((i) => i <= 0));
}
// listen();
// waitFor();
// isEmpty();
// any();
// contains();
// join() ;
// skipAndTake();
// skipAndTakeWhile(); // Look Until the condition is broken
// where(); // Look for all coming elemts
// distinct(); // get only one data if it yield more than one time
// mix();
transform();
///******* OnError Handing video 5 *********///
{
/* there is 2 types of error methods one in the listen funcation
* te other is an method of the stream class
*/
// getNum()
// .handleError((error)=>print(error))// only execute if error happen and stop the Stream
// .listen((data)=>print(data) );
// timesOut returns exception if there is no stream event
// getNum()
// .timeout(Duration(seconds: 4))
// .listen(print);
}
///******* Stream Controller video 6 *********///
{
/* used to send data to that Stream
* This controller allows sending data, error and done events on its stream.
* This class can be used to create a simple stream that others can listen on, and to push events to that stream.
*/
}
}
Stream<int> getNumbersDuplicates() async* {
for (var i = 1; i <= 4; i++) {
yield i;
await Future.delayed(Duration(seconds: 1));
// yield i;
yield i+2;
await Future.delayed(Duration(seconds: 1));
}
}
Stream<int> getNum() async*{
for(int i = 0 ; i<=3 ;i++){
await Future.delayed(Duration(seconds: 1));
yield i ;
// if( i==3) throw Exception();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment