How to work with progress indicator in flutter?

后端 未结 12 810
面向向阳花
面向向阳花 2020-12-02 05:29

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,

12条回答
  •  情书的邮戳
    2020-12-02 06:07

    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 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 {
      Future user;
    
      void _logIn() {
        setState(() {
          user = new Future.delayed(const Duration(seconds: 3), () {
            return new MyUser("Toto");
          });
        });
      }
    
      Widget _buildForm(AsyncSnapshot 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: [
                      floatBtn,
                      new CircularProgressIndicator(
                        backgroundColor: Colors.red,
                      ),
                    ],
                  )
                : floatBtn;
    
        return new ListView(
          padding: const EdgeInsets.all(15.0),
            children: [
              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 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),
              );
            }
          },
        );
      }
    }
    

提交回复
热议问题