Created
December 6, 2019 10:32
-
-
Save tarek360/0335b3f07c5db0e37021be421284b220 to your computer and use it in GitHub Desktop.
StreamBuilder Example
This file contains hidden or 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'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
final StreamController<String> _events = StreamController<String>(); | |
void _showError(String message) { | |
_events.add(message); | |
} | |
@override | |
Widget build(BuildContext context) { | |
print('build...'); | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('StreamBuilder'), | |
), | |
body: Center( | |
child: StreamBuilder<String>( | |
stream: _events.stream, | |
initialData: 'No Errors', | |
builder: (BuildContext context, AsyncSnapshot<String> snapshot) { | |
return ErrorView(snapshot.data); | |
}, | |
), | |
), | |
floatingActionButton: Column( | |
mainAxisAlignment: MainAxisAlignment.end, | |
children: <Widget>[ | |
FloatingActionButton( | |
onPressed: () => _showError('Printing Error!'), | |
child: Icon(Icons.print), | |
), | |
FloatingActionButton( | |
onPressed: () => _showError('Translation Error!'), | |
child: Icon(Icons.translate), | |
), | |
], | |
), | |
); | |
} | |
} | |
class ErrorView extends StatelessWidget { | |
const ErrorView(this.message); | |
final String message; | |
@override | |
Widget build(BuildContext context) { | |
return Text( | |
message, | |
style: TextStyle(color: Colors.red), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment