Flutter not showing CircularProgressIndicator - flutter

I'm developing simple webview applicatoin using flutter , here i used CircularProgressIndicator but its not showing.
Package i use: https://pub.dev/packages/flutter_webview_plugin
How i can show the loading using CircularProgressIndicator in flutter ?, I'm using stack to show the loading indicator the centor of it.
class _MyHomePageState extends State<MyHomePage> {
final flutterWebViewPlugin = FlutterWebviewPlugin();
bool isLoading = true;
double webProgress = 0;
#override
void initState() {
super.initState();
flutterWebViewPlugin.onProgressChanged.listen((double progress) {
setState(() {
this.webProgress = progress;
});
print("The progress is $progress");
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: WillPopScope(
onWillPop: () async {
print("back pressed");
return false;
},
child: Stack(
children: [
Column(
children: [
webProgress < 1
? SizedBox(
height: 5,
child: LinearProgressIndicator(
value: webProgress,
color: Colors.blue,
backgroundColor: Colors.white,
),
)
: SizedBox(),
Expanded(
child: WebviewScaffold(
url: "https://google.com",
mediaPlaybackRequiresUserGesture: false,
withLocalStorage: true,
),
),
],
),
isLoading
? Center(
child: CircularProgressIndicator(
color: Colors.red,
),
)
: Stack(),
],
),
),
));
}
}

Related

how to close web view in flutter on button click

I am working on flutter app where i redirect to web view for certain operation and after the operation is success on a button click i want to come back to app by closing the web view. Giving navigator.pop() on button click is not closing the web view, it just navigate back to previous page in web.any solution for this issue. attatching my web view and final success page with this.
class PlansWebView extends StatefulWidget {
final String token;
const PlansWebView({Key key, this.token}) : super(key: key);
#override
_PlansWebViewState createState() => _PlansWebViewState();
}
class _PlansWebViewState extends State<PlansWebView> {
bool isLoading = true;
bool _dstReached = false;
WebViewController _webViewController;
#override
Widget build(BuildContext context) {
_dstReached ? Navigator.pop(context) : print('plans web view page');
print(widget.token);
return Stack(children: <Widget>[
WebView(
javascriptMode: JavascriptMode.unrestricted,
onPageFinished: (finish) {
setState(() {
isLoading = false;
});
},
initialUrl:
'my webview link',
onWebViewCreated: (webViewController) =>
_webViewController = webViewController,
navigationDelegate: (NavigationRequest request) {
if (request.url == 'webviewlink/#/signin') {
setState(() {
_dstReached = true;
});
Navigator.pop(context);
// do not navigate
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
isLoading
? Center(
child: CircularProgressIndicator(
color: Colors.red,
),
)
: Stack(),
]);
}
}
below is the code where i have put a button and on that button click i want to close web view.
class Success extends StatefulWidget {
Success({Key key}) : super(key: key);
#override
_SuccessState createState() => _SuccessState();
}
class _SuccessState extends State<Success> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
addPayment(addPaymentFields);
final Size screenSize = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Color(0xFFFFFFFF),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
EmptySection(
'assets/images/success.gif',
'Successful !!',
),
SubTitle(
'Your payment was done successfully',
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: COLORS['PRIMARY_COLOR']),
onPressed: () {
Navigator.pushNamedAndRemoveUntil(
context, '/signin', (route) => false);
},
child: Text('Sign In')
)
],
),
);
}
}
Widget SubTitle(String subTitleText) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0),
child: Text(
subTitleText,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18.0,
color: Color(0xFF808080),
),
),
);
}
Widget EmptySection(emptyImg, emptyMsg) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image(
image: AssetImage(emptyImg),
height: 150.0,
),
Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Text(
emptyMsg,
style: TextStyle(
fontSize: 20.0,
color: Color(0xFF303030),
),
),
),
],
));
}

How to push to a new screen in Flutter without the appbar from the previous screen in Flutter?

I have two screens. In screen1 I have an appbar and a card in the body. IF I click the card it should take me to new screen 'screen2'. I am getting the screen2 but I am also getting the appbar from screen1 as well.. I am doing a push from screen1 to screen2.. May I know how to avoid the appbar from the screen1 in screen2? I have onTap method in VideoCard widget which pushes to screen2... it looks like body of the screen1 is being replaced by screen2.. instead i need to push to screen2 from screen1...
enter image description here
class _AllVideosPageTabletState extends State<AllVideosPageTablet> {
bool searchFlag = false;
String searchText = '';
#override
void initState() {
searchFlag = false;
searchText = '';
super.initState();
}
#override
Widget build(BuildContext context) {
final isLandscape = MediaQuery.of(context).orientation ==
Orientation.landscape;
return Scaffold(
body: Container(
padding: EdgeInsets.all(10.0),
child: Column(
children: [
CupertinoSearchTextField(
onChanged: (value) {
if (value != '') {
setState(
() {
searchFlag = true;
searchText = value;
},
);
}
},
onSubmitted: (value) {
if (value != '') {
setState(
() {
searchFlag = true;
searchText = value;
},
);
}
},
),
Divider(),
Row(
children: [
IconButton(
icon: Image.asset('lib/assets/icons/back.png'),
onPressed: () {
Navigator.pop(context);
},
),
Expanded(
child: Container(
child: Center(
child: Text(
'All Videos',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: '#D86300'.toColor(),
),
),
),
),
),
],
),
searchFlag
? SearchResultsListView(searchText)
: Expanded(
child: FutureBuilder(
future: VideoXML().getDataFromXML(context),
builder: (context, data) {
if (data.hasData) {
List<Video> videoList = data.data;
return GridView.count(
scrollDirection: Axis.vertical,
crossAxisCount: isLandscape ? 4 : 2,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
children: videoList.map(
(video) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: VideoCard(
video.title,
video.name,
video.image,
),
);
},
).toList(),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
),
],
),
),
);
}
Flutter works in a way that every new screen is based on a new Scaffold widget. This way you can customize, whether to show the appBar at all or should be display different appBar on different screens.
For example:
Screen 1 should be a scaffold of its own:
class FirstScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:'Screen 1'),
body: InkWell(onTap: () => Navigator.of(context).pushedName(routeToSecondScreen),
child: Text('Navigate to secondScreen'),
);
);
}
}
Screen 2 should be a scaffold of its own:
class SecondScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title:'Screen 2'),
body: Text('Screen 2'),
);
}
}
This way you can have different appBars for each screen. If you do not wish to display appBar on the second screen at all, simply do not specify appBar on the second screen as follows.
class SecondScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Text('Screen 2'),
);
}
}

Flutter - CircularProgressIndicator won't stop executing

My problem is that the CircularProgressIndicator won't stop buffering. My goal is when the video detects a lagging status then the CircularProgressIndicator will show and when it plays again then the CircularProgressIndicator will stop showing.
bool vidBuffering = true;
void buffer() {
setState(() {
vidBuffering = !vidBuffering;
});
}
This is inside a widget where I call the vidBuffering
Widget _buildPlayStack() {
return Stack(
children: [
_buildPlay(),
child: FlatButton(
onPressed: () => setState(() {
_vidController.value.isPlaying ? _vidController.pause() :_vidController.play();
}),
child: Center(
child: (_vidController.value.isPlaying)
? Icon(Icons.pause, color: Colors.green)
: Icon(Icons.play_arrow, color: Colors.green),
),
),
Center(
child: _vidBuffering
? const CircularProgressIndicator()
: null),
],
);
}
Widget _buildPlay() {
return Container(
child: AspectRatio(
aspectRatio: _vidController.value.aspectRatio,
child: VideoPlayer(_controller),
),
);
}
You should be used StreamBuilder for update only Loader
For Example :
class Demo extends StatefulWidget {
#override
_DemoState createState() => _DemoState();
}
class _DemoState extends State<Demo> {
bool vidBuffering = true;
StreamController streamControllerBuffering = StreamController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildPlayStack(),
RaisedButton(
onPressed: () => buffer(),
child: Text(vidBuffering ? 'Hide' : 'Show'),
)
],
),
),
);
}
void buffer() {
vidBuffering = !vidBuffering;
streamControllerBuffering.sink.add(vidBuffering);
}
Widget _buildPlayStack() {
return Stack(
children: [
_buildPlay(),
FlatButton(
onPressed: () => setState(() {
/*_vidController.value.isPlaying
? _vidController.pause()
: _vidController.play();*/
}),
child: Center(
child: (/*_vidController.value.isPlaying*/ true)
? Icon(Icons.pause, color: Colors.green)
: Icon(Icons.play_arrow, color: Colors.green),
),
),
Center(
child: StreamBuilder(
initialData: true,
stream: streamControllerBuffering.stream,
builder: (builder, snapshot) {
if (snapshot.hasData && snapshot.data) {
return CircularProgressIndicator();
} else {
Offstage();
}
return Offstage();
}),
),
],
);
}
Widget _buildPlay() {
return Container(
height: 200,
width: 200,
color: Colors.amber,
);
}
#override
void dispose() {
streamControllerBuffering.close();
super.dispose();
}
}

AppBar in flutter

I have designed a news application in flutter where I have an app bar with tabs following it. In the tabbarview I have a list of news. on click of the news, it will show details description and image of the news(as shown in the image). When I try to put the app bar in that file. Two app bar appears. What would the possible way sort it out?
Here is the code:
appBar: AppBar(
title: Text(""),
backgroundColor: Color(0xFF125688), //#125688 //FFFF1744
actions: <Widget>[
Container(
alignment: Alignment.topRight,
child: FlatButton(
onPressed: () {},
padding: EdgeInsets.fromLTRB(0, 10.0, 8.0, 0),
child: Text(
date,
style: TextStyle(
color: Colors.white,
),
)),
)
],
bottom: TabBar(
tabs: <Widget>[
Tab(text: "TOP-HEADLINES"),
Tab(text: "LATEST-NEWS"),
Tab(text: "SPORTS"),
Tab(text: "CRIME-NEWS"),
],
isScrollable: true,
),
),
body: TabBarView(children: [
TopHeadlines(),
LatestNews(),
Sports(),
CrimeNews(),
],
),
CODE FOR TOPHEADLINES()
class TopHeadlines extends StatefulWidget {
int index;
String value_image,value_description,value_title;
TopHeadlines({Key key,this.value_image,this.value_description,this.value_title,this.index}) : super(key:key);
#override
_topHeadlines createState() => _topHeadlines();
}
class _topHeadlines extends State<TopHeadlines> {
List<News> dataList = List();
bool _isLoading = false;
BuildContext context1;
Future<String> loadFromAssets() async {
DateTime oops = DateTime.now();
String d_date = DateFormat('ddMMyyyy').format(oops);
var url = 'https://www.example.com/json-12.json';
print(url);
var response = await http
.get('$url', headers: {"charset": "utf-8", "Accept-Charset": "utf-8"});
String utfDecode = utf8.decode(response.bodyBytes);
return utfDecode;
}
Future loadyourData() async {
setState(() {
_isLoading = true;
});
String jsonString = await loadFromAssets();
String newStr = jsonString.substring(1, jsonString.length - 1);
print(newStr);
Map newStringMap = json.decode(newStr);
var list = new List();
newStringMap.forEach((key, value) {
list.add(value);
});
for (var newsList in list) {
var news = News.fromJson(newsList);
dataList.add(news);
}
print('This is the length' + dataList.length.toString());
print(dataList[0].title);
setState(() {
_isLoading = false;
});
}
#override
void initState() {
super.initState();
loadyourData();
}
#override
Widget build(BuildContext context) {
DateTime oops = DateTime.now();
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Container(
child: _isLoading ? Center(
child: CircularProgressIndicator(),) :
ListView.builder(
itemCount: dataList.length, itemBuilder: (context, index) {
return SizedBox(
height: 130.0,
child: Card(
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
InkWell(
onTap: (){
// dataList;
Navigator.push(context, MaterialPageRoute(builder: (context) {
print(index);
return Newsdetail(value_image: dataList[index].image,value_description: dataList[index].description,value_title: dataList[index].title, );
}));
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: Image.network(
dataList[index].image,
height: 92.5,
width: 75.0,
)),
Expanded(
child: Text(
dataList[index].title,
style: TextStyle(
//title
fontSize: 15.0, color: Colors.grey,
),
),
)
],
),
),
),
],
),
),
);
},
),
));
}
}
Remove the appBars from these views:
TopHeadlines(),
LatestNews(),
Sports(),
CrimeNews(),
Only return the Content you want to display by return a Container or the widget you want to display

How to work with progress indicator in flutter?

I'm newbie in flutter and wanted to know what is better way to add CircularProgressIndicator in my layout. For example, my login view. This view have username, password and login Button. I did want create a overlay layout (with Opacity) that, when loading, show progress indicator like I use in NativeScript, but I'm little confused with how to do and too if it is the better way. On NativeScript, for example, I add IndicatorActivity in main layout and set busy to true or false, so it overlay all view components when is loading.
Edit:
I was able to reach this result:
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _loading = false;
void _onLoading() {
setState(() {
_loading = true;
new Future.delayed(new Duration(seconds: 3), _login);
});
}
Future _login() async{
setState((){
_loading = false;
});
}
#override
Widget build(BuildContext context) {
var body = new Column(
children: <Widget>[
new Container(
height: 40.0,
padding: const EdgeInsets.all(10.0),
margin: const EdgeInsets.fromLTRB(15.0, 150.0, 15.0, 0.0),
decoration: new BoxDecoration(
color: Colors.white,
),
child: new TextField(
decoration: new InputDecoration.collapsed(hintText: "username"),
),
),
new Container(
height: 40.0,
padding: const EdgeInsets.all(10.0),
margin: const EdgeInsets.all(15.0),
decoration: new BoxDecoration(
color: Colors.white,
),
child: new TextField(
decoration: new InputDecoration.collapsed(hintText: "password"),
),
),
],
);
var bodyProgress = new Container(
child: new Stack(
children: <Widget>[
body,
new Container(
alignment: AlignmentDirectional.center,
decoration: new BoxDecoration(
color: Colors.white70,
),
child: new Container(
decoration: new BoxDecoration(
color: Colors.blue[200],
borderRadius: new BorderRadius.circular(10.0)
),
width: 300.0,
height: 200.0,
alignment: AlignmentDirectional.center,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Center(
child: new SizedBox(
height: 50.0,
width: 50.0,
child: new CircularProgressIndicator(
value: null,
strokeWidth: 7.0,
),
),
),
new Container(
margin: const EdgeInsets.only(top: 25.0),
child: new Center(
child: new Text(
"loading.. wait...",
style: new TextStyle(
color: Colors.white
),
),
),
),
],
),
),
),
],
),
);
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Container(
decoration: new BoxDecoration(
color: Colors.blue[200]
),
child: _loading ? bodyProgress : body
),
floatingActionButton: new FloatingActionButton(
onPressed: _onLoading,
tooltip: 'Loading',
child: new Icon(Icons.check),
),
);
}
}
I'm still adapting to the idea of ​​states. This code is within the expected when working with flutter?
In flutter, there are a few ways to deal with Asynchronous actions.
A lazy way to do it can be using a modal. Which will block the user input, thus preventing any unwanted actions.
This would require very little change to your code. Just modifying your _onLoading to something like this :
void _onLoading() {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Dialog(
child: new Row(
mainAxisSize: MainAxisSize.min,
children: [
new CircularProgressIndicator(),
new Text("Loading"),
],
),
);
},
);
new Future.delayed(new Duration(seconds: 3), () {
Navigator.pop(context); //pop dialog
_login();
});
}
The most ideal way to do it is using FutureBuilder and a stateful widget. Which is what you started.
The trick is that, instead of having a boolean loading = false in your state, you can directly use a Future<MyUser> user
And then pass it as argument to FutureBuilder, which will give you some info such as "hasData" or the instance of MyUser when completed.
This would lead to something like this :
#immutable
class MyUser {
final String name;
MyUser(this.name);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<MyUser> user;
void _logIn() {
setState(() {
user = new Future.delayed(const Duration(seconds: 3), () {
return new MyUser("Toto");
});
});
}
Widget _buildForm(AsyncSnapshot<MyUser> snapshot) {
var floatBtn = new RaisedButton(
onPressed:
snapshot.connectionState == ConnectionState.none ? _logIn : null,
child: new Icon(Icons.save),
);
var action =
snapshot.connectionState != ConnectionState.none && !snapshot.hasData
? new Stack(
alignment: FractionalOffset.center,
children: <Widget>[
floatBtn,
new CircularProgressIndicator(
backgroundColor: Colors.red,
),
],
)
: floatBtn;
return new ListView(
padding: const EdgeInsets.all(15.0),
children: <Widget>[
new ListTile(
title: new TextField(),
),
new ListTile(
title: new TextField(obscureText: true),
),
new Center(child: action)
],
);
}
#override
Widget build(BuildContext context) {
return new FutureBuilder(
future: user,
builder: (context, AsyncSnapshot<MyUser> snapshot) {
if (snapshot.hasData) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Hello ${snapshot.data.name}"),
),
);
} else {
return new Scaffold(
appBar: new AppBar(
title: new Text("Connection"),
),
body: _buildForm(snapshot),
);
}
},
);
}
}
For me, one neat way to do this is to show a SnackBar at the bottom while the Signing-In process is taken place, this is a an example of what I mean:
Here is how to setup the SnackBar.
Define a global key for your Scaffold
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
Add it to your Scaffold key attribute
return new Scaffold(
key: _scaffoldKey,
.......
My SignIn button onPressed callback:
onPressed: () {
_scaffoldKey.currentState.showSnackBar(
new SnackBar(duration: new Duration(seconds: 4), content:
new Row(
children: <Widget>[
new CircularProgressIndicator(),
new Text(" Signing-In...")
],
),
));
_handleSignIn()
.whenComplete(() =>
Navigator.of(context).pushNamed("/Home")
);
}
It really depends on how you want to build your layout, and I am not sure what you have in mind.
Edit
You probably want it this way, I have used a Stack to achieve this result and just show or hide my indicator based on onPressed
class TestSignInView extends StatefulWidget {
#override
_TestSignInViewState createState() => new _TestSignInViewState();
}
class _TestSignInViewState extends State<TestSignInView> {
bool _load = false;
#override
Widget build(BuildContext context) {
Widget loadingIndicator =_load? new Container(
color: Colors.grey[300],
width: 70.0,
height: 70.0,
child: new Padding(padding: const EdgeInsets.all(5.0),child: new Center(child: new CircularProgressIndicator())),
):new Container();
return new Scaffold(
backgroundColor: Colors.white,
body: new Stack(children: <Widget>[new Padding(
padding: const EdgeInsets.symmetric(vertical: 50.0, horizontal: 20.0),
child: new ListView(
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center
,children: <Widget>[
new TextField(),
new TextField(),
new FlatButton(color:Colors.blue,child: new Text('Sign In'),
onPressed: () {
setState((){
_load=true;
});
//Navigator.of(context).push(new MaterialPageRoute(builder: (_)=>new HomeTest()));
}
),
],),],
),),
new Align(child: loadingIndicator,alignment: FractionalOffset.center,),
],));
}
}
Create a bool isLoading and set it to false. With the help of ternary operator, When user clicks on login button set state of isLoading to true. You will get circular loading indicator in place of login button
isLoading ? new PrimaryButton(
key: new Key('login'),
text: 'Login',
height: 44.0,
onPressed: setState((){isLoading = true;}))
: Center(
child: CircularProgressIndicator(),
),
You can see Screenshots how it looks while before login is clicked
After login is clicked
In mean time you can run login process and login user. If user credentials are wrong then again you will setState of isLoading to false, such that loading indicator will become invisible and login button visible to user.
By the way, primaryButton used in code is my custom button. You can do same with OnPressed in button.
Step 1: Create Dialog
showAlertDialog(BuildContext context){
AlertDialog alert=AlertDialog(
content: new Row(
children: [
CircularProgressIndicator(),
Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
],),
);
showDialog(barrierDismissible: false,
context:context,
builder:(BuildContext context){
return alert;
},
);
}
Step 2: Call it
showAlertDialog(context);
await firebaseAuth.signInWithEmailAndPassword(email: email, password: password);
Navigator.pop(context);
Example Dialog and login form
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class DynamicLayout extends StatefulWidget{
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return new MyWidget();
}
}
showAlertDialog(BuildContext context){
AlertDialog alert=AlertDialog(
content: new Row(
children: [
CircularProgressIndicator(),
Container(margin: EdgeInsets.only(left: 5),child:Text("Loading" )),
],),
);
showDialog(barrierDismissible: false,
context:context,
builder:(BuildContext context){
return alert;
},
);
}
class MyWidget extends State<DynamicLayout>{
Color color = Colors.indigoAccent;
String title='app';
GlobalKey<FormState> globalKey=GlobalKey<FormState>();
String email,password;
login() async{
var currentState= globalKey.currentState;
if(currentState.validate()){
currentState.save();
FirebaseAuth firebaseAuth=FirebaseAuth.instance;
try {
showAlertDialog(context);
AuthResult authResult=await firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser user=authResult.user;
Navigator.pop(context);
}catch(e){
print(e);
}
}else{
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar:AppBar(
title: Text("$title"),
) ,
body: Container(child: Form(
key: globalKey,
child: Container(
padding: EdgeInsets.all(10),
child: Column(children: <Widget>[
TextFormField(decoration: InputDecoration(icon: Icon(Icons.email),labelText: 'Email'),
// ignore: missing_return
validator:(val){
if(val.isEmpty)
return 'Please Enter Your Email';
},
onSaved:(val){
email=val;
},
),
TextFormField(decoration: InputDecoration(icon: Icon(Icons.lock),labelText: 'Password'),
obscureText: true,
// ignore: missing_return
validator:(val){
if(val.isEmpty)
return 'Please Enter Your Password';
},
onSaved:(val){
password=val;
},
),
RaisedButton(color: Colors.lightBlue,textColor: Colors.white,child: Text('Login'),
onPressed:login),
],)
,),)
),
);
}
}
Example from Ui
1. Without plugin
class IndiSampleState extends State<ProgHudPage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
2. With plugin
check this plugin progress_hud
add the dependency in the pubspec.yaml file
dev_dependencies:
progress_hud:
import the package
import 'package:progress_hud/progress_hud.dart';
Sample code is given below to show and hide the indicator
class ProgHudPage extends StatefulWidget {
#override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
#override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
I took the following approach, which uses a simple modal progress indicator widget that wraps whatever you want to make modal during an async call.
The example in the package also addresses how to handle form validation while making async calls to validate the form (see flutter/issues/9688 for details of this problem). For example, without leaving the form, this async form validation method can be used to validate a new user name against existing names in a database while signing up.
https://pub.dartlang.org/packages/modal_progress_hud
Here is the demo of the example provided with the package (with source code):
Example could be adapted to other modal progress indicator behaviour (like different animations, additional text in modal, etc..).
This is my solution with stack
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
final themeColor = new Color(0xfff5a623);
final primaryColor = new Color(0xff203152);
final greyColor = new Color(0xffaeaeae);
final greyColor2 = new Color(0xffE8E8E8);
class LoadindScreen extends StatefulWidget {
LoadindScreen({Key key, this.title}) : super(key: key);
final String title;
#override
LoginScreenState createState() => new LoginScreenState();
}
class LoginScreenState extends State<LoadindScreen> {
SharedPreferences prefs;
bool isLoading = false;
Future<Null> handleSignIn() async {
setState(() {
isLoading = true;
});
prefs = await SharedPreferences.getInstance();
var isLoadingFuture = Future.delayed(const Duration(seconds: 3), () {
return false;
});
isLoadingFuture.then((response) {
setState(() {
isLoading = response;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
),
centerTitle: true,
),
body: Stack(
children: <Widget>[
Center(
child: FlatButton(
onPressed: handleSignIn,
child: Text(
'SIGN IN WITH GOOGLE',
style: TextStyle(fontSize: 16.0),
),
color: Color(0xffdd4b39),
highlightColor: Color(0xffff7f7f),
splashColor: Colors.transparent,
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0)),
),
// Loading
Positioned(
child: isLoading
? Container(
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(themeColor),
),
),
color: Colors.white.withOpacity(0.8),
)
: Container(),
),
],
));
}
}
You can do it for center transparent progress indicator
Future<Null> _submitDialog(BuildContext context) async {
return await showDialog<Null>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return SimpleDialog(
elevation: 0.0,
backgroundColor: Colors.transparent,
children: <Widget>[
Center(
child: CircularProgressIndicator(),
)
],
);
});
}
{
isloading? progressIos:Container()
progressIos(int i) {
return Container(
color: i == 1
? AppColors.liteBlack
: i == 2 ? AppColors.darkBlack : i == 3 ? AppColors.pinkBtn : '',
child: Center(child: CupertinoActivityIndicator()));
}
}
You can use FutureBuilder widget instead. This takes an argument which must be a Future. Then you can use a snapshot which is the state at the time being of the async call when loging in, once it ends the state of the async function return will be updated and the future builder will rebuild itself so you can then ask for the new state.
FutureBuilder(
future: myFutureFunction(),
builder: (context, AsyncSnapshot<List<item>> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
//Send the user to the next page.
},
);
Here you have an example on how to build a Future
Future<void> myFutureFunction() async{
await callToApi();}
Centered on screen:
Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [CircularProgressIndicator()])
])
class Loader extends StatefulWidget {
#override
State createState() => LoaderState();
}
class LoaderState extends State<Loader> with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> animation;
#override
void initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: 1200), vsync: this);
animation = CurvedAnimation(parent: controller, curve: Curves.elasticOut);
animation.addListener(() {
this.setState(() {});
});
animation.addStatusListener((AnimationStatus status) {});
controller.repeat();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
color: Colors.blue,
height: 3.0,
width: animation.value * 100.0,
),
Padding(
padding: EdgeInsets.only(bottom: 5.0),
),
Container(
color: Colors.blue[300],
height: 3.0,
width: animation.value * 75.0,
),
Padding(
padding: EdgeInsets.only(bottom: 5.0),
),
Container(
color: Colors.blue,
height: 3.0,
width: animation.value * 50.0,
)
],
);
}
}
Expanded(
child: Padding(
padding:
EdgeInsets.only(left: 20.0, right: 5.0, top:20.0),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FirstScreen()));
},
child: Container(
alignment: Alignment.center,
height: 45.0,
decoration: BoxDecoration(
color: Color(0xFF1976D2),
borderRadius: BorderRadius.circular(9.0)),
child: Text('Login',
style: TextStyle(
fontSize: 20.0, color: Colors.white))),
),
),
),
For your case, maybe it can be done by using showing a modal with a circle indicator. But I recommend using a simple plugin https://pub.dev/packages/flutter_easyloading.
The installation supper easy. Just run this flutter pub add flutter_easyloading in your terminal
Put this in you main.dart app
import 'package:flutter/material.dart';
import 'package:kunjungi_dokter/pages/welcome.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart'; // <- add this
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: const Welcome(),
builder: EasyLoading.init(), // <- add this
);
}
}
To show the modal or the loading widget, in my case I show it in mya _login function in Login Screen:
import 'package:flutter_easyloading/flutter_easyloading.dart';
// ... other code
_login() async {
EasyLoading.show(status: 'loading...', maskType: EasyLoadingMaskType.black); // code to show modal with masking
var data = await LoginAPI.connectToAPI(
emailController.text, passwordController.text);
if (data.isError) {
EasyLoading.showError('Login Error: ' + data.message); // code to show modal without masking and auto close
} else {
await storage.write(key: 'token', value: data.token);
await storage.write(key: 'email', value: emailController.text);
EasyLoading.showSuccess('Login Success!'); // code to show modal without masking and auto close
Navigator.of(context)
.push(MaterialPageRoute(builder: ((context) => const Home())));
}
}
// ... other code
Tips, you can use this to close the modal:
EasyLoading.dismiss();
You will need a library for it
void onLoading() {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return GFLoader(
type: GFLoaderType.android,
);
},
);
}
and then use this function where you need in code
onLoading;