0

I have FutureBuilder inside an AlertDialog box. Initially, on clicking a floating action button a alertdialog opens in which there is a submit button.On clicking it I call another function with FutureBuilder inside it because I want to show a loading icon inside same AlertDialog box while fetching data replacing whole previous content.On successful fetch of data I want to Navigate the user to new page popping that alertdialog box. But it appears the future of futurebuilder is working but builder is not.I tried using StatefulBuilder but it not seemed to be helping.

Dialog Box function

Future<void> _showMyDialog() async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: Text('Your Image'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(18.0),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8.0),
                      child: Image.file(File(image.path)),
                    ),
                  ),
                  Container(

                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        RaisedButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },

                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Icon(Icons.clear_rounded),
                              Text('Cancel'),
                            ],
                          ),
                          color: Colors.white,
                          textColor: avtar_backGround1,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5.0),
                              side: BorderSide(width: 0.1)),
                          padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                        ),
                        RaisedButton(
                          onPressed: () {
                            setState(() {
                              imageUploader(myImage, widget.token);
                            });
                            print("##############134");
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Icon(Icons.upload_rounded),
                              Text('Submit'),
                            ],
                          ),
                          color: avtar_backGround1,
                          textColor: Colors.white,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(5.0),
                              side: BorderSide(width: 0.1)),
                          padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }
        );
      },
    );
  }

The FutureBuilder function:

FutureBuilder imageUploader(PickedFile myImage,String token) {
    return FutureBuilder(
      future: imageFutureCaller(myImage,token),
      builder: (BuildContext context, AsyncSnapshot snapshot){
        if (snapshot.hasError) {
          print("++++++++ ${snapshot.error}");
          return Center(
            child: Container(
              child: Text(
                '${snapshot.error} occured',
                style: TextStyle(fontSize: 18),
              ),
            ),
          );
        }
        else if(snapshot.hasData){
          if(snapshot.data==true){
            print("fffffffff");
             Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                    builder: (context) =>
                        Confetti()));
                 return Container(height: 0.0,width: 0.0,);
          }
          else{
            return Container(child: Text("Sorry!, Image not uploaded"));
          }
        }
        else{
          return Center(
            child:CircularProgressIndicator()
          );
        }
      },
    );
  }

Future function

Future<bool> imageFutureCaller(PickedFile myImage, String token) async {
    try {
      String filename = myImage.path.toString();
    
      var request = await http.MultipartRequest(
          'POST', Uri.parse('http://green-earth.herokuapp.com/uploadphoto'));
      request.headers['authorization'] = 'Bearer '+token;
     
      request.files.add(await http.MultipartFile.fromPath('image', filename));
    var res = await request.send();
 
    if (res.statusCode == 200) {
    print("image uploaded");
    _dataAvailable=true;
    successfulUploadedDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
    return true;
    } else {
    _dataAvailable=true;
    return false;
    print('error');
    }
    } catch (e) {
    print(e);
    print("image not uploaded");
    }
  }
}

In future I am returning the bool value i.e. either true or false. Also Help me with Navigation too on successful data fetch.

Gautam Goyal
  • 230
  • 1
  • 4
  • 16

1 Answers1

0

Make imageUploader as an async function and await for result.

Future<bool> imageUploader(PickedFile myImage,String token) async {
  final result = await imageFutureCaller(myImage,token);
}

and onPressed await for the result.

onPressed: () async {
    final result = await imageUploader(myImage, widget.token);
    if (result) {
      Navigator.pop(context);
      // do something
    }
  },
Mohan Sai Manthri
  • 2,808
  • 1
  • 11
  • 26
  • where is futurebuilder inside imageuploader function? I have added the code for my future call function. I need futurebuilder to show progress indicator and error text. ADDED – Gautam Goyal Mar 29 '21 at 13:09
  • I have one question, You are returning some widgets in imageuploader, but where you showing them? I mean in onPressed function you are not referencing, except the setState, so Where are you showing the returned widgets? I can help you better If I can know this. – Mohan Sai Manthri Mar 29 '21 at 13:29
  • I was thinking that die to stateful builder it will automatically change content in dialog box on setting staten with the content of future builder in the function imageUploader. But if it's not correct then suggest the way plz. – Gautam Goyal Mar 29 '21 at 14:15