Last active
July 24, 2020 09:49
-
-
Save GAM3RG33K/62022944239a91d94534b15d43c74c20 to your computer and use it in GitHub Desktop.
[Flutter] Show progress bar based on the response of a method using streams and stream builder
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 '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 { | |
| @override | |
| Widget build(BuildContext context) { | |
| return baseBuilder(context); | |
| } | |
| /// This method shows how your code should be framed for showing a progress bar based | |
| /// on the return value of a normal method | |
| Widget baseBuilder(context) { | |
| return StreamBuilder<bool>( | |
| initialData: true, | |
| stream: _longOperation(), | |
| builder: (context, snapshot) { | |
| final isLoading = snapshot?.data ?? true; | |
| return Stack( | |
| children: <Widget>[ | |
| Container( | |
| child: Center( | |
| child: Text('Base Widget : $isLoading'), | |
| ), | |
| ), | |
| Visibility( | |
| visible: isLoading, | |
| child: Center( | |
| child: CircularProgressIndicator(), | |
| ), | |
| ), | |
| ], | |
| ); | |
| }, | |
| ); | |
| } | |
| /// you can use any return type but should be able to distinguish when to start | |
| /// and when to stop the progress bar | |
| /// like, `null` for showing and `not null` for hiding progress bar | |
| Stream<bool> _longOperation() async* { | |
| yield true; | |
| //do some long operation instead of wait | |
| await Future.delayed( | |
| Duration( | |
| seconds: 5, | |
| ), | |
| ); | |
| yield false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment