Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a Loading Indicator while waiting for API response

So I have a registration page and the register function works well. Now all I need is just a loading indicator after pressing the "Register" button.
I've mixed all the keywords I could think of to search in google and I've tried them all but nothing's working.

Here are the things I've tried:

using FutureBuilder:

RaisedButton(
                    onPressed: () async {
                      FutureBuilder<http.Response>(
                        future: registerUser(),
                        builder: (context, snapshot) {
                          if (snapshot.hasData) {
                            return Text("SUCCESS");
                          }
                          if (snapshot.hasError) {
                            return Text("ERROR");
                          }
                          return new Center(
                              child: new CircularProgressIndicator());
                        },
                      );
                    },
                    color: Color(colorPrimary),
                    shape: RoundedRectangleBorder(
                        borderRadius: new BorderRadius.circular(30.0)),
                    child: Text("SignUp"),
                  )

in this one, the method is called but the indicator is not showing

using a library progress_hud: This one I think is working but even if I place this inside a Center Widget, it still goes to the bottom of the screen which gives an overlapping with pixels error.

are there any other better solutions? or should I just find a way to fix this overlapping error?

Thanks for your help!

like image 464
nerdy kid Avatar asked Sep 25 '19 07:09

nerdy kid


2 Answers

please use package modal_progress_hud https://pub.dev/packages/modal_progress_hud
ModalProgressHUD must under scaffold body as first child
my working code snippet

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ModalProgressHUD(
        inAsyncCall: _isLoading,
        child: SingleChildScrollView(
          child: Container(
               ...

full example code

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LoginPage(
        onSignIn: () => print('login successful!'),
      ),
    );
  }
}

class LoginPage extends StatefulWidget {
  final VoidCallback _onSignIn;

  LoginPage({@required onSignIn})
      : assert(onSignIn != null),
        _onSignIn = onSignIn;

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // maintains validators and state of form fields
  final GlobalKey<FormState> _loginFormKey = GlobalKey<FormState>();

  // manage state of modal progress HUD widget
  bool _isInAsyncCall = false;

  bool _isInvalidAsyncUser = false; // managed after response from server
  bool _isInvalidAsyncPass = false; // managed after response from server

  String _username;
  String _password;
  bool _isLoggedIn = false;

  // validate user name
  String _validateUserName(String userName) {
    if (userName.length < 8) {
      return 'Username must be at least 8 characters';
    }

    if (_isInvalidAsyncUser) {
      // disable message until after next async call
      _isInvalidAsyncUser = false;
      return 'Incorrect user name';
    }

    return null;
  }

  // validate password
  String _validatePassword(String password) {
    if (password.length < 8) {
      return 'Password must be at least 8 characters';
    }

    if (_isInvalidAsyncPass) {
      // disable message until after next async call
      _isInvalidAsyncPass = false;
      return 'Incorrect password';
    }

    return null;
  }

  void _submit() {
    if (_loginFormKey.currentState.validate()) {
      _loginFormKey.currentState.save();

      // dismiss keyboard during async call
      FocusScope.of(context).requestFocus(new FocusNode());

      // start the modal progress HUD
      setState(() {
        _isInAsyncCall = true;
      });

      // Simulate a service call
      Future.delayed(Duration(seconds: 1), () {
        final _accountUsername = 'username1';
        final _accountPassword = 'password1';
        setState(() {
          if (_username == _accountUsername) {
            _isInvalidAsyncUser = false;
            if (_password == _accountPassword) {
              // username and password are correct
              _isInvalidAsyncPass = false;
              _isLoggedIn = true;
            } else
              // username is correct, but password is incorrect
              _isInvalidAsyncPass = true;
          } else {
            // incorrect username and have not checked password result
            _isInvalidAsyncUser = true;
            // no such user, so no need to trigger async password validator
            _isInvalidAsyncPass = false;
          }
          // stop the modal progress HUD
          _isInAsyncCall = false;
        });
        if (_isLoggedIn)
          // do something
          widget._onSignIn();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Modal Progress HUD Demo'),
        backgroundColor: Colors.blue,
      ),
      // display modal progress HUD (heads-up display, or indicator)
      // when in async call
      body: ModalProgressHUD(
        child: SingleChildScrollView(
          child: Container(
            padding: const EdgeInsets.all(16.0),
            child: buildLoginForm(context),
          ),
        ),
        inAsyncCall: _isInAsyncCall,
        // demo of some additional parameters
        opacity: 0.5,
        progressIndicator: CircularProgressIndicator(),
      ),
    );
  }

  Widget buildLoginForm(BuildContext context) {
    final TextTheme textTheme = Theme.of(context).textTheme;
    // run the validators on reload to process async results
    _loginFormKey.currentState?.validate();
    return Form(
      key: this._loginFormKey,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextFormField(
              key: Key('username'),
              decoration: InputDecoration(
                  hintText: 'enter username', labelText: 'User Name'),
              style: TextStyle(fontSize: 20.0, color: textTheme.button.color),
              validator: _validateUserName,
              onSaved: (value) => _username = value,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextFormField(
              key: Key('password'),
              obscureText: true,
              decoration: InputDecoration(
                  hintText: 'enter password', labelText: 'Password'),
              style: TextStyle(fontSize: 20.0, color: textTheme.button.color),
              validator: _validatePassword,
              onSaved: (value) => _password = value,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(32.0),
            child: RaisedButton(
              onPressed: _submit,
              child: Text('Login'),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: _isLoggedIn
                ? Text(
              'Login successful!',
              key: Key('loggedIn'),
              style: TextStyle(fontSize: 20.0),
            )
                : Text(
              'Not logged in',
              key: Key('notLoggedIn'),
              style: TextStyle(fontSize: 20.0),
            ),
          ),
        ],
      ),
    );
  }
}

enter image description here

like image 128
chunhunghan Avatar answered Sep 28 '22 02:09

chunhunghan


FutureBuilder puts its generated body in the widget it's attached to. Otherwise, where does the returned Widget go?

Example with Material Scaffold

Scaffold(
  appBar:AppBar(),
  body: FutureBuilder(
   future: registerUser(),
   builder: (context,snapshot){
    //...
   }
  )
)

The problem is, your future is bound to a RaisedButton's on pressed. Secondly, you are probably better off using a StreamBuilder,since FutureBuilder calls it's future immediately in the build method. So instead, call your BLoC/ViewModel/wathever to do registerUser(). Let registerUser() return a Future<void> (and internally adds the result to a Stream). Then observe the Stream for a result or error. For Streams/Sinks, you can use StreamController<T>.

//In your form Widget

RaisedButton(
 onPressed: registerUser()
)

//In your Widget/BLoC/ViewModel
//Note that the Future can finish with errors from the http call
//call registerUser() with an onError callback to catch these.
//And the Stream can finish with errors(although this is unlikely here)
//the Stream.listen() can also have an onError callback 

Future<void> registerUser() async {
 var result = await http.post();

 //then finally pass it to the stream
 _stream.add(result);
}
like image 45
Navaron Bracke Avatar answered Sep 28 '22 02:09

Navaron Bracke