Created
January 9, 2022 16:12
-
-
Save xros/829e57e41e2bfd8777d35812ae4d4cca to your computer and use it in GitHub Desktop.
StreamController from dart:async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
void addLessThanFive(StreamController controller, int value) { | |
if (value < 5) { | |
controller.sink.add(value); | |
} else { | |
controller.sink.addError(StateError('$value is not less than 5')); | |
} | |
} | |
void main() { | |
final controller = StreamController(); | |
addLessThanFive(controller, 1); | |
addLessThanFive(controller, 2); | |
addLessThanFive(controller, 3); | |
addLessThanFive(controller, 4); | |
addLessThanFive(controller, 5); | |
controller.stream.listen( (value) { | |
print(value); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In pure Dart, we use
StreamController
to handleStream
objectIn Flutter framework, we use
StreamBuilder
as a widget to handleStream
object. We call each item in the Stream assnapshot
. And withsnapshot
inside of the StreamBuilder, we can judgesnapshot.connectionState
and passsnapshot.data
out.snapshot.data
is an item stored in the Stream object.Demo codes
file auth.dart
File landing_page.dart
So on different pages/widgets, we can call and judge variables asynchronously easily.
StreamBuilder solves this question in the past
With StreamBuilder, life is easier.
So on different pages/widgets, we can call and judge variables asynchronously easily.
Here in the codes, StreamBuilder builds a producer in the class
Auth
-authStateChanges()
which returns aUser
object, and in the classLandingPage
has a consumerStreamBuilder<User>
, which checkssnapshot.connectionState
infinitely.If the
User
object is changed, the classLandingPage
will redirect to other widget with variables. In this case, the variable isauth
object --SignInPage(auth: auth)
orHomePage(auth: auth)
.