簡體   English   中英

顯示循環進度指示器,異步任務

[英]Show circular progress indicator, async task

我試圖在運行異步任務時顯示一個循環進度指示器。 異步任務由單擊按鈕觸發,並且還將用戶引導至新頁面。 代碼如下所示:

child: GestureDetector(
   onTap: () async{

     //some async task that takes a few seconds

     Navigator.push( ...
}

我希望用戶在單擊按鈕時首先看到一個圓形進度指示器,並且當任務完成時,他應該被引導到另一個屏幕。 但我不知道如何向他展示這個進度指示器。 提前感謝您的回答!

你可以使用這個庫https://pub.dev/packages/simpleprogressdialog

創建ProgressDialog的object

ProgressDialog progressDialog = ProgressDialog(context: context, barrierDismissible: false);

然后在您的異步任務之前調用showMaterial

progressDialog.showMaterial(layout: MaterialProgressDialogLayout.overlayWithCircularProgressIndicator);

然后在異步任務之后,關閉對話框。

progressDialog.dismiss();

我對你想要的做了一點模擬:

檢查下面的代碼:

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  // boolean variable to decide when to show progress indicator
  bool showProgress = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: InkWell(
          onTap: () async {
            // set the progress indicator to true so it will be visible
            setState(() {
              showProgress = true;
            });
            // perform asynchronous task here
            await Future.delayed(Duration(seconds: 4), null);

            setState(() {
              // set the progress indicator to true so it would not be visible
              showProgress = false;
              // navigate to your desired page
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => AnotherScreen()));
            });
          },
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Your widgets can stay here',
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(
                height: 20,
              ),
              Container(
                height: 50,
                width: 50,
                color: Colors.blue,
                child: Center(
                  // use ternary operator to decide when to show progress indicator
                  child: showProgress
                      ? CircularProgressIndicator()
                      : Text('Tap me'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

檢查下面的 output:

Output 這里

注意:為簡單起見(使用了上面的示例)。 避免多次調用setState 您可以使用 state 管理技術,例如BlocProvider ,並且可能決定使用服務定位器進行注入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM