Как отображать всплывающее окно с CircularProgressIndicator и статусом загрузки, когда я нажимаю кнопку загрузки - PullRequest
0 голосов
/ 25 мая 2020

Я пытаюсь создать приложение, которое может загружать изображения. Я хочу, чтобы при нажатии кнопки загрузки отображалось всплывающее окно с CircularProgressIndicator и статусом загрузки. Всякий раз, когда я нажимаю кнопку загрузки, изображение загружается в фоновом режиме, но на экране ничего не отображается.

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class HomePage extends StatefulWidget {
 @override
 _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
 final imgUrl =
     'https://images.unsplash.com/photo-1503023345310-bd7c1de61c7d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80';
 bool downloading = false;
 var progressString = " ";

 @override
 void initState() {
   super.initState();
   downloadFile();
 }

 // Downloading image using Dio package
 Future<void> downloadFile() async {
   Dio dio = Dio();
   try {
     var dir = await getApplicationDocumentsDirectory();
     await dio.download(imgUrl, "${dir.path}/DownloadedImage.jpg",
         onReceiveProgress: (rec, total) {
       print("rec: $rec, total: $total");
       setState(() {
         downloading = true;
         progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
       });
     });
   } catch (e) {
     print(e);
   }

   setState(() {
     progressString = "Download Completed";
     downloading = false;
   });
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     body: Container(
         child: Column(
       mainAxisAlignment: MainAxisAlignment.center,
       children: <Widget>[
         Center(
           child: RaisedButton.icon(
             onPressed: () {
               downloadFile();
             },
             icon: Icon(Icons.file_download),
             label: Text('Download'),
             color: Colors.blueAccent,
           ),
         )
       ],
     )),
   );
 }
}

Я хочу показать этот контейнер, как при нажатии кнопки

  Container(
                 height: 120.0,
                 width: 200.0,
                 child: Card(
                   color: Colors.black54,
                   child: Column(
                     mainAxisAlignment: MainAxisAlignment.center,
                     children: <Widget>[
                       CircularProgressIndicator(),
                       SizedBox(
                         height: 10.0,
                       ),
                       Text('Downloading $progressString'),
                     ],
                   ),
                 ),
               );

1 Ответ

1 голос
/ 25 мая 2020

Вы можете отобразить всплывающее диалоговое окно, используя showDialog.

static Future showDialog(BuildContext context, GlobalKey _key) async   {
  return showLoadingDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context){
      return SimpleDialog(
          key: _key,
          children: <Widget>[
            Center(
              child: Container(
                child: Row(
                children: <Widget>[
                  CircularProgressIndicator(),
                  SizedBox(
                    height:10,
                    width:10,
                  ),
                  Text("Please Wait!"),
                ]
             ),
          ],
        ),
      );
    }
  );
}

Здесь GlobalKey используется для Show или hide созданного диалогового окна.

Для вызова этого просто инициализировать GlobalKey в классе как GlobalKey<State> _dialogKey = GlobalKey<State>();.

Затем вы можете отобразить диалог как:

showLoadingDialog(context, _dialogKey);

И когда вы хотите, чтобы он скрылся, просто позвоните:

Navigator.of(_dialogKey.currentContext,rootNavigator: true).pop();

Надеюсь, это поможет.

...