Last active
February 3, 2020 19:18
-
-
Save lesliearkorful/b2883a94467caebcc8271cb4a59ef7e2 to your computer and use it in GitHub Desktop.
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'; | |
import 'package:flutter/material.dart'; | |
final Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue), | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: MyWidget(), | |
), | |
), | |
); | |
} | |
} | |
class MyWidget extends StatelessWidget { | |
final Bloc bloc = Bloc(); | |
@override | |
Widget build(BuildContext context) { | |
// trigger event | |
bloc.getUser(); | |
return StreamBuilder<UserModel>( | |
stream: bloc.stream, | |
builder: (context, snapshot) { | |
// show loader while stream is null | |
if (snapshot?.data == null) return CircularProgressIndicator(); | |
// build ui after completion | |
// you may implement some stuff to check for errors | |
return Text('Hello ${snapshot.data?.username ?? "User"}'); | |
}, | |
); | |
} | |
} | |
class Bloc { | |
StreamController<UserModel> _controller = StreamController<UserModel>(); | |
Stream<UserModel> get stream => _controller.stream; | |
Sink<UserModel> get sink => _controller.sink; | |
getUser() { | |
// The delay is to fake a (network) request | |
Future.delayed(Duration(seconds: 2), () { | |
sink.add(UserModel(username: 'Oniya Daniel')); | |
}); | |
} | |
void dispose() => _controller.close(); | |
} | |
class UserModel { | |
String username; | |
UserModel({this.username}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment