flutterdartasync-awaitflutter-getxget-cli

how can i close a Get overlay in flutter?


I have an async function in my application and the user should wait unlit the operation is completed but there should be a button that cancels the operation and restest the operation in the app the problem is when i use getx's overley it is fine but the cancel btn does not work i searched every where and still nothing

await Get.showOverlay(asyncFunction: () async {
      //-------------------Example for the operation----------
      await Future.delayed(Duration(seconds: 5));
    }, loadingWidget: Material(
      color: Colors.transparent,
      type: MaterialType.transparency,
      elevation: 0,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('working on...',style: TextStyle(color: Colors.white,fontSize: 20,fontFamily: 'Sans',),),
          SizedBox(height: 10.0,),
          CircularProgressIndicator(color: Colors.blue),
          BtnWidget(text: 'cancle', icon: Assets.svg.cancelSvgrepoCom, onPressed: () {
            Get.back();
            restartsteps();
          })
        ],
      ),
    ));

i appreciate any help

i used Get.back() but it goes to previous page and the overlay is still open untill the operation finishes i used Get.back(closeOverlays: true); and Get.close(1), nothing worked yet


Solution

  • Future are not stoppable in middle of execution.

    You can combine Timer with Completer to complete it from your Timer and await on Completer.future like this:

    final Completer<bool> completer = Completer();
    late Timer timer;
        
    await Get.showOverlay(asyncFunction: () 
             async {
              timer = Timer(Duration(seconds: 10), () {
              completer.complete(true);
              });
              await completer.future;
            },
            loadingWidget: Material(
              color: Colors.transparent,
              type: MaterialType.transparency,
              elevation: 0,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'working on...',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontFamily: 'Sans',
                    ),
                  ),
                  SizedBox(
                    height: 10.0,
                  ),
                  CircularProgressIndicator(color: Colors.blue),
                  ElevatedButton(
                    onPressed: () {
                      timer.cancel();
                      completer.complete(true);
                    },
                    child: Text("cancel"),
                  )
                ],
              ),
            ));