【问题标题】:Flutter - How can I add a circular loading indicator to my button?Flutter - 如何向我的按钮添加圆形加载指示器?
【发布时间】:2020-11-23 20:03:06
【问题描述】:

我有一个 Flutter 代码。我不想在单击提交按钮时不显示任何内容,而是希望在单击按钮时显示圆形加载指示器,以便让用户保持忙碌,但我面临着将我拥有的教程转换为工作的挑战我的代码。

教程如下:

...
 children: <Widget>[
            new Padding(
              padding: const EdgeInsets.all(16.0),
              child: new MaterialButton(
                child: setUpButtonChild(),
                onPressed: () {
                  setState(() {
                    if (_state == 0) {
                      animateButton();
                    }
                  });
                },
                elevation: 4.0,
                minWidth: double.infinity,
                height: 48.0,
                color: Colors.lightGreen,
              ),
            )
          ],
 Widget setUpButtonChild() {
    if (_state == 0) {
      return new Text(
        "Click Here",
        style: const TextStyle(
          color: Colors.white,
          fontSize: 16.0,
        ),
      );
    } else if (_state == 1) {
      return CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
      );
    } else {
      return Icon(Icons.check, color: Colors.white);
    }
  }

  void animateButton() {
    setState(() {
      _state = 1;
    });

    Timer(Duration(milliseconds: 1000), () {
      setState(() {
        _state = 2;
      });
    });

    Timer(Duration(milliseconds: 3300), () {
       Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => AnchorsPage(),
        ),
      );
    });
  }

这是我的代码。我要做的就是在系统执行 HTTP 请求时显示CircularProgressIndicator

这是我想使用CircularProgressIndicator的代码:

                           Center(

                            child: 
                            RaisedButton(
                              padding: EdgeInsets.fromLTRB(80, 10, 80, 10),
                              color: Colors.green,
                             
                              child: setUpButtonChild(),
                             
                              onPressed: ()  {

                                setState(()async {
                                _state = 1;
                                var toSubmit = {
                                  "oid": EopOid,
                                  "modifiedBy": user['UserName'].toString(),
                                  "modifiedOn": DateTime.now().toString(),
                                  "submitted": true,
                                  "submittedOn": DateTime.now().toString(),
                                  "submittedBy": user['UserName'].toString()
                                };
                                for (EopLine i in selectedEops) {
                                  var item = {
                                    "oid": i.oid.toString(),
                                    "quantityCollected": i.quantityCollected,
                                    "modifiedBy": user['UserName'].toString(),
                                    "modifiedOn": DateTime.now().toString(),
                                  };
                                  await http
                                      .put(
                                          "http://api.ergagro.com:112/UpdateEopLine",
                                          headers: {
                                            'Content-Type': 'application/json'
                                          },
                                          body: jsonEncode(item))
                                      .then((value) async {
                                    if (selectedEops.indexOf(i) ==
                                        selectedEops.length - 1) {
                                      await http
                                          .put(
                                              "http://api.ergagro.com:112/SubmitEop",
                                              headers: {
                                                'Content-Type':
                                                    'application/json'
                                              },
                                              body: jsonEncode(toSubmit))
                                          .then((value) {
                                        print('${value.statusCode} submitted');
                                        Navigator.pop(context);
                                      });
                                    }
                                  });
                                }
                               _state = 2;
                                });
                              //Navigator.of(context).push(MaterialPageRoute(
                              //builder: (context) =>
                              //StartScanPage(widget.dc_result)));
                              },
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(50),
                              ),
                            ),
                          ),

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies flutter-web


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    可以直接使用包https://pub.dev/packages/progress_indicator_button
    或参考它的源代码
    您可以将AnimationController 传递给http 工作并使用controller.forwardreset

    代码sn-p

    void httpJob(AnimationController controller) async {
        controller.forward();
        print("delay start");
        await Future.delayed(Duration(seconds: 3), () {});
        print("delay stop");
        controller.reset();
      }
    ...  
    ProgressButton(
            borderRadius: BorderRadius.all(Radius.circular(8)),
            strokeWidth: 2,
            child: Text(
              "Sample",
              style: TextStyle(
                color: Colors.white,
                fontSize: 24,
              ),
            ),
            onPressed: (AnimationController controller) async {
              await httpJob(controller);
            }
    

    工作演示

    完整代码

    import 'package:flutter/material.dart';
    import 'package:progress_indicator_button/progress_button.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
    
      void _incrementCounter() {
        setState(() {
          _counter++;
        });
      }
    
      void httpJob(AnimationController controller) async {
        controller.forward();
        print("delay start");
        await Future.delayed(Duration(seconds: 3), () {});
        print("delay stop");
        controller.reset();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: 200,
                  height: 60,
                  child: ProgressButton(
                    borderRadius: BorderRadius.all(Radius.circular(8)),
                    strokeWidth: 2,
                    child: Text(
                      "Sample",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                      ),
                    ),
                    onPressed: (AnimationController controller) async {
                      await httpJob(controller);
                    },
                  ),
                ),
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      你也可以使用三元运算符根据_isLoading状态变量进行输出,并利用CircularProgressIndicator(),当然这是一个简单的解决方案,不使用任何第三方库。

        @override
        Widget build(BuildContext context) {
          return TextButton(
            onPressed: () {},
            child: Container(
              padding: const EdgeInsets.all(10),
              child: _isLoading
                  ? SizedBox(
                      height: 25,
                      width: 25,
                      child: CircularProgressIndicator(),
                    )
                  : Text('ORDER NOW'),
            ),
          );
        }
      

      【讨论】:

        【解决方案3】:

        如果您正在使用带有icon() 构造函数(图标+文本)的按钮,则可以在按钮状态更改时将图标与CircularProgressIndicator 交换。它之所以有效,是因为图标和指示器都是小部件:

        return ElevatedButton.icon(
          onPressed: _isLoading ? null : _onSubmit,
          style: ElevatedButton.styleFrom(padding: const EdgeInsets.all(16.0)),
          icon: _isLoading
              ? Container(
                  width: 24,
                  height: 24,
                  padding: const EdgeInsets.all(2.0),
                  child: const CircularProgressIndicator(
                    color: Colors.white,
                    strokeWidth: 3,
                  ),
                )
              : const Icon(Icons.feedback),
          label: const Text('SUBMIT'),
        );
        

        Live Demo

        【讨论】:

          猜你喜欢
          • 2014-06-08
          • 2020-11-03
          • 2015-07-05
          • 1970-01-01
          • 1970-01-01
          • 2011-06-03
          • 2019-12-24
          • 2020-01-13
          • 1970-01-01
          相关资源
          最近更新 更多