fayaz07 / progress_dialog

A light weight library to easily manage a progress dialog with simple steps whenever you need to do it. You can easily show and hide it.

Home Page:https://fayaz07.github.io/progress_dialog/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

call Navigator.pop in pr.hide().whenComplete 80% not poping out

carlhung opened this issue · comments

i want to pop out the route, but 80% of times it doesn't work.

pr.hide().whenComplete((){
Navigator.pop(context, xxx);
});

I confirm, mine too

Can you show me the sample code to reproduce

Hello there @fayaz07 i do have the same issue i will share my code with you

bool isHidden = await pr.hide(); if(isHidden){ Navigator.of(context).pop(); }

When i debug my code it works fine , but when i use it as normal it doesn't work . as the guys above mentioned sometimes it works sometimes not

@khamisEDX , can you post full page sample code

class AddUser extends StatefulWidget {
  final Map<String, dynamic> data;
  AddUser(this.data);
  @override
  _AddUserState createState() => _AddUserState();
}

class _AddUserState extends State<AddUser> {
  MyModel model;
  CustomDio customDio;
  TextEditingController emailTEC;
  TextEditingController fisrtNameTEC;
  TextEditingController lastNameTEC;
  TextEditingController phoneNumberTEC;
  TextEditingController designationTEC;
  String mobileNumber;
  String mobileNumberFormData;
  String phoneIsoCode = "";
  bool visible = false;
  String confirmedNumber = '';
  bool enabled = true;
  bool pointOfContact = false;
  bool overrideSMS = false;
  bool sendNotification = false;
  Map test;
  List<String> list;
  bool isInternalUser = false;
  ProgressDialog pr;

  @override
  void initState() {
    super.initState();
    pr = new ProgressDialog(context);
    emailTEC = new TextEditingController();
    fisrtNameTEC = new TextEditingController();
    lastNameTEC = new TextEditingController();
    phoneNumberTEC = new TextEditingController();
    designationTEC = new TextEditingController();
    model = widget.data[Constants.MODEL];
    model.onInitStateChooseDefaultValue(RouteGenerater.ADMIN_ADD);
    customDio = new CustomDio(context, new Dio(), model);
    getApiData();
    permissionAndPolicy();
  }

  @override
  void dispose() {
    super.dispose();
    // wholePolicy
    model.onDisposeWholePolicy();
    emailTEC.dispose();
    fisrtNameTEC.dispose();
    lastNameTEC.dispose();
    phoneNumberTEC.dispose();
    designationTEC.dispose();
  }

  permissionAndPolicy() {
    if (Constants.internalUsers
        .contains(model.userPolicyAndRoleID['role_id'].toString())) {
      isInternalUser = true;
    }

    model.userPolicyAndRoleID['user_policy']['Member Portal'].forEach((list) {
      var map = new Map<String, List<String>>();
      map[list.keys.toList()[0]] = new List<String>();
      model.updateWholePolicy(map);
    });
  }

  void onPhoneNumberChange(
      String number, String internationalizedPhoneNumber, String isoCode) {
    setState(() {
      phoneIsoCode = internationalizedPhoneNumber.substring(0, internationalizedPhoneNumber.length - number.length);
      mobileNumber = number;
      mobileNumberFormData = "$phoneIsoCode-$number";
    });
  }

  onValidPhoneNumber(
      String number, String internationalizedPhoneNumber, String isoCode) {
    setState(() {
      visible = true;
      confirmedNumber = internationalizedPhoneNumber;
    });
  }

  getApiData() async {
    if (model.allRoles.isEmpty) {
      await customDio.getAllFiltersAdminLIST(true, 23, null);
      await customDio.getAllFiltersAdminLIST(true, 25, null);
    }
  }

  Future<void> onPressed() async {
      pr.style(
        insetAnimCurve: Curves.easeInOut,
        backgroundColor: Colors.white,
        borderRadius: 10.0,
        progressWidget: Container(
            padding: EdgeInsets.all(8.0),
            child: CircularProgressIndicator(
              backgroundColor: AllColors.primary,
            )),
      );
      
    Map<String, dynamic> formData = new Map<String, dynamic>();
    Map<String, dynamic> message = new Map<String, dynamic>();

    formData['account_enabled'] = enabled;
    formData['sms_otp_override'] = overrideSMS;
    formData['point_of_contact'] = pointOfContact;
    formData['send_email'] = sendNotification;

    if (emailTEC.text.isEmpty) {
      message['Email'] = null;
    } else {
      formData['email'] = emailTEC.text;
    }
    if (fisrtNameTEC.text.isEmpty) {
      message['First Name'] = null;
    } else {
      formData['first_name'] = fisrtNameTEC.text;
    }
    if (lastNameTEC.text.isEmpty) {
      message['Last Name'] = null;
    } else {
      formData['last_name'] = lastNameTEC.text;
    }
    if (model.selectedRole.id == null) {
      message['Role'] = null;
    }

    if (mobileNumberFormData == null || mobileNumberFormData.isEmpty) {
      message['Mobile number'] = null;
    } else {
      formData["mobile_number"] = mobileNumberFormData;
    }

    if (designationTEC.text.isEmpty) {
      message['Desination'] = null;
    } else {
      formData['designation'] = designationTEC.text;
    }
    // check (choose a type)
    if (model.wholePolicy.isEmpty) {
      message['Policy'] = null;
    }

    if (model.selectedNotification.isEmpty) {
      message['Components'] = "are required";
    }

    if (model.selectedMemberGroupAddUser.isEmpty) {
      message['Member group'] = null;
    }

    if (message.isEmpty) {
      pr.show();
      var res = await customDio.adminAddUser(true, formData);
      if(res != null){
        if(!res.containsKey(Constants.CACHE_ERROR)){
          bool isHidden = await pr.hide();
          if(isHidden){
          customShowDialogYesNo(context, AppLocalizations.of(context).tr("addSA_Success_msg"), AppLocalizations.of(context).tr("addUser_admin_msg") ,
           (){
             Navigator.of(context).pop();
           }, false);
        }
        }
      }
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => DialogValidation(
              {Constants.MODEL: model, Constants.WRONG_DATA: message}));
    }
    // print('''
    //   All member group => ${model.selectedMemberGroupAddUser.toString()}
    //   Email => ${emailTEC.text}
    //   firstName => ${fisrtNameTEC.text}
    //   LastName => ${lastNameTEC.text}
    //   Roles => ${model.selectedRole.name}
    //   Mobile Phone => ${mobileNumber.toString()}
    //   Phone Number => ${phoneNumberTEC.text}
    //   Designation => ${designationTEC.text}
    //   Choose Type => ${model.selectedNotification.toString()}
    //   Send Notification => $sendNotification

    //   Enabled => $enabled
    //   Points of Contact => $pointOfContact
    //   OverrideSMS => $overrideSMS


    //   Policy => ${model.wholePolicy}

    //   ''');
  }

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<MyModel>(
      builder: (_, child, dontusethis) {
        return Scaffold(
          bottomNavigationBar:
              RaisedButton(child: Text('temp button'), onPressed: onPressed),
          appBar: CustomizedAppbar(
            model: model,
            route: RouteGenerater.ADMIN_ADD,
            showArrow: true,
            title: "admin_add_title",
          ),
          body: model.allRoles.isEmpty //&& model.allNotifications.isEmpty
              ? Center(
                  child: CircularProgressIndicator(
                    backgroundColor: AllColors.primary,
                  ),
                )
              : ListView(
                  shrinkWrap: true,
                  children: <Widget>[
                    model.isMultiSelect
                        ? Container(
                            //height: 100,
                            margin: const EdgeInsets.only(
                                left: 10.0, right: 10.0, bottom: 5.0, top: 10),
                            padding: const EdgeInsets.all(3.0),
                            color: Colors.transparent,
                            child: new Container(
                              decoration: new BoxDecoration(
                                  color: Colors.white,
                                  border: new Border.all(
                                    color: Color(0xFFBDBDBD),
                                    width: 2,
                                  ),
                                  borderRadius: new BorderRadius.circular(12)),
                              child: DropdownButtonHideUnderline(
                                child: SearchableDropdown.multiple(
                                  isCaseSensitiveSearch: false,
                                  clearIcon: Icon(null),
                                  dialogBox: true,
                                  displayClearIcon: false,
                                  doneButton: false,
                                  isExpanded: true,
                                  underline: "",
                                  hint: "All member groups",
                                  searchHint: "All member groups",
                                  selectedItems: model
                                      .selectedMemberGroupAddUser
                                      .map((e) => model.allMemberGroupsAddUser
                                          .indexWhere(
                                              (element) => element.id == e.id))
                                      .toList(),
                                  items: model.allMemberGroupsAddUser.map((e) {
                                    return DropdownMenuItem(
                                      value: e.id,
                                      child: Text(e.name),
                                    );
                                  }).toList(),
                                  onChanged: (List<int> value) {
                                    for (int item in value) {
                                      model
                                          .addAndRemoveFromListTilesCheckBoxesByCode(
                                              24,
                                              true,
                                              model.allMemberGroupsAddUser[
                                                  item]);
                                    }
                                  },
                                ),
                              ),
                            ))
                        : createSpinnerItem(
                            code: 24,
                            context: context,
                            model: model,
                            dataList: model.allMemberGroupsAddUser,
                            headingSpinner: "",
                            item: model.selectedMemberGroupAddUser[0]),
                    textField(emailTEC, "Email"),
                    textField(fisrtNameTEC, "First Name"),
                    textField(lastNameTEC, "Last Name"),
                    createSpinnerItem(
                        code: 23,
                        context: context,
                        model: model,
                        dataList: model.allRoles,
                        headingSpinner: "",
                        item: model.selectedRole),
                    Container(
                        height: 50,
                        margin: const EdgeInsets.only(
                            left: 10.0, right: 10.0, bottom: 5.0, top: 10),
                        padding: const EdgeInsets.all(3.0),
                        color: Colors.transparent,
                        child: new Container(
                          decoration: new BoxDecoration(
                              color: Colors.white,
                              border: new Border.all(
                                color: Color(0xFFBDBDBD),
                                width: 2,
                              ),
                              borderRadius: new BorderRadius.circular(12)),
                          child: Center(
                            child: InternationalPhoneInput(
                              decoration: InputDecoration(
                                //counterText: '',
                                //enabled: true,
                                //helperText: '',
                                //isDense: false,
                                contentPadding:
                                    EdgeInsets.symmetric(vertical: 15),
                                border: InputBorder.none,
                                focusedErrorBorder: InputBorder.none,
                                focusedBorder: InputBorder.none,
                                enabledBorder: InputBorder.none,
                                //errorBorder: InputBorder.none,
                                disabledBorder: InputBorder.none,
                              ),
                              onPhoneNumberChange: onPhoneNumberChange,
                              initialPhoneNumber: mobileNumber,
                              initialSelection: phoneIsoCode,
                              labelText: "Phone Number",
                            ),
                          ),
                        )),
                    textField(phoneNumberTEC, "Phone Number"),
                    textField(designationTEC, "Designation"),
                    createSpinnerMultipleSelection(
                        code: 25,
                        context: context,
                        model: model,
                        headingSpinner: '',
                        dataList: model.allNotifications,
                        item: model.selectedNotification,
                        label: model.selectedNotificationLabel),
                    SwitchListTile(
                        title: Text("Send Notification"),
                        activeColor: AllColors.primary,
                        value: sendNotification,
                        onChanged: (newValue) {
                          setState(() {
                            sendNotification = newValue;
                          });
                        }),
                    SwitchListTile(
                        title: Text("Enabled"),
                        activeColor: AllColors.primary,
                        value: enabled,
                        onChanged: (newValue) {
                          setState(() {
                            enabled = newValue;
                          });
                        }),
                    SwitchListTile(
                        title: Text("Point of Contacts"),
                        activeColor: AllColors.primary,
                        value: pointOfContact,
                        onChanged: (newValue) {
                          setState(() {
                            pointOfContact = newValue;
                          });
                        }),
                    SwitchListTile(
                        title: Text("Override SMS"),
                        activeColor: AllColors.primary,
                        value: overrideSMS,
                        onChanged: (newValue) {
                          setState(() {
                            overrideSMS = newValue;
                          });
                        }),
                    Container(height: 20),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.all(10.0),
                      child: Table(
                          columnWidths: {
                            0: FlexColumnWidth(2.0),
                            1: FlexColumnWidth(1.0),
                            2: FlexColumnWidth(1.0),
                          },
                          border: TableBorder.all(
                              color: Colors.black.withOpacity(0.2)),
                          children: [
                            TableRow(children: [
                              TableCell(
                                  verticalAlignment:
                                      TableCellVerticalAlignment.middle,
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text(
                                      "Module",
                                      textAlign: TextAlign.left,
                                    ),
                                  )),
                              TableCell(
                                  verticalAlignment:
                                      TableCellVerticalAlignment.middle,
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text(
                                      "View",
                                      textAlign: TextAlign.left,
                                    ),
                                  )),
                              TableCell(
                                  verticalAlignment:
                                      TableCellVerticalAlignment.middle,
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text(
                                      "Add",
                                      textAlign: TextAlign.left,
                                    ),
                                  )),
                              TableCell(
                                  verticalAlignment:
                                      TableCellVerticalAlignment.middle,
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text(
                                      "Edit",
                                      textAlign: TextAlign.left,
                                    ),
                                  )),
                              TableCell(
                                  verticalAlignment:
                                      TableCellVerticalAlignment.middle,
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: Text(
                                      "Delete",
                                      textAlign: TextAlign.left,
                                    ),
                                  )),
                            ]),
                            for (Map item in model.wholePolicy)
                              TableRow(children: [
                                TableCell(
                                    verticalAlignment:
                                        TableCellVerticalAlignment.middle,
                                    child: Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Text(
                                        item.keys.toList()[0],
                                        textAlign: TextAlign.left,
                                      ),
                                    )),
                                TableCell(
                                  child: Center(
                                    child: Switch(
                                        activeColor: AllColors.primary,
                                        value: item[item.keys.toList()[0]]
                                                .contains("View")
                                            ? true
                                            : false,
                                        onChanged: (val) {
                                          setState(() {
                                            item[item.keys.toList()[0]].contains("View")
                                                ? {
                                                  item[item.keys.toList()[0]].contains("Add") ? 
                                                  item[item.keys.toList()[0]].remove("Add") : null ,
                                                  item[item.keys.toList()[0]].contains("Edit") ? 
                                                  item[item.keys.toList()[0]].remove("Edit") : null ,
                                                  item[item.keys.toList()[0]].contains("Delete") ? 
                                                  item[item.keys.toList()[0]].remove("Delete") : null ,
                                                  item[item.keys.toList()[0]].remove("View"),
                                                  
                                                }:
                                                 item[item.keys.toList()[0]].add("View");

                                          });
                                        }),
                                  ),
                                ),
                                TableCell(
                                  child: Center(
                                    child: Switch(
                                        activeColor: AllColors.primary,
                                        value: item[item.keys.toList()[0]]
                                                .contains("Add")
                                            ? true
                                            : false,
                                        onChanged: (val) {
                                          setState(() {
                                            item[item.keys.toList()[0]].contains("Add")
                                                ? item[item.keys.toList()[0]]
                                                    .remove("Add")
                                                : item[item.keys.toList()[0]].add("Add");

                                          });
                                        }),
                                  ),
                                ),
                                TableCell(
                                  child: Center(
                                    child: Switch(
                                        activeColor: AllColors.primary,
                                        value: item[item.keys.toList()[0]]
                                                .contains("Edit")
                                            ? true
                                            : false,
                                        onChanged: (val) {
                                          setState(() {
                                            item[item.keys.toList()[0]]
                                                    .contains("Edit")
                                                ? item[item.keys.toList()[0]]
                                                    .remove("Edit")
                                                : item[item.keys.toList()[0]]
                                                    .add("Edit");

                                          });
                                        }),
                                  ),
                                ),
                                TableCell(
                                  child: Center(
                                    child: Switch(
                                        activeColor: AllColors.primary,
                                        value: item[item.keys.toList()[0]]
                                                .contains("Delete")
                                            ? true
                                            : false,
                                        onChanged: !isInternalUser
                                            ? null
                                            : (val) {
                                                setState(() {
                                                  item[item.keys.toList()[0]]
                                                          .contains("Delete")
                                                      ? item[item.keys
                                                              .toList()[0]]
                                                          .remove("Delete")
                                                      : item[item.keys
                                                              .toList()[0]]
                                                          .add("Delete");

                                                });
                                              }),
                                  ),
                                ),
                              ])
                          ]),
                    )
                  ],
                ),
        );
      },
    );
  }
}

Widget textField(TextEditingController tec, String hint) {
  return Container(
      height: 40,
      margin:
          const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 5.0, top: 10),
      padding: const EdgeInsets.all(3.0),
      color: Colors.transparent,
      child: new Container(
        decoration: new BoxDecoration(
            color: Colors.white,
            border: new Border.all(
              color: Color(0xFFBDBDBD),
              width: 2,
            ),
            borderRadius: new BorderRadius.circular(12)),
        child: TextFormField(
          controller: tec,
          decoration: new InputDecoration(
              border: InputBorder.none,
              focusedBorder: InputBorder.none,
              enabledBorder: InputBorder.none,
              errorBorder: InputBorder.none,
              disabledBorder: InputBorder.none,
              contentPadding:
                  EdgeInsets.only(left: 8, bottom: 11, top: 11, right: 8),
              hintText: hint),
        ),
      ));
}

@khamisEDX can you make it a bit simple :)

@khamisEDX can you make it a bit simple :)

Yes sorry for the previous 👍

@fayaz07 any news ?

Sorry @khamisEDX can you give me shorter code

Basically this is the function you need to see @fayaz07

Future<void> onPressed() async {
      pr.style(
        insetAnimCurve: Curves.easeInOut,
        backgroundColor: Colors.white,
        borderRadius: 10.0,
        progressWidget: Container(
            padding: EdgeInsets.all(8.0),
            child: CircularProgressIndicator(
              backgroundColor: AllColors.primary,
            )),
      );
      
    Map<String, dynamic> formData = new Map<String, dynamic>();
    Map<String, dynamic> message = new Map<String, dynamic>();

    if (emailTEC.text.isEmpty) {
      message['Email'] = null;
    } else {
      formData['email'] = emailTEC.text;
    }
    if (fisrtNameTEC.text.isEmpty) {
      message['First Name'] = null;
    } else {
      formData['first_name'] = fisrtNameTEC.text;
    }
  
    if (message.isEmpty) {
      pr.show();
      var res = await customDio.adminAddUser(true, formData);
      if(res != null){
        if(!res.containsKey(Constants.CACHE_ERROR)){
          bool isHidden = await pr.hide();
          if(isHidden){
          customShowDialogYesNo(context, AppLocalizations.of(context).tr("addSA_Success_msg"), AppLocalizations.of(context).tr("addUser_admin_msg") ,
           (){
             Navigator.of(context).pop();
           }, false);
        }
        }
      }
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => DialogValidation(
              {Constants.MODEL: model, Constants.WRONG_DATA: message}));
    }
  }

the problem was not using await in show() , so using await for both hide && show , you can use this class i made if you want to be a singleton class

class ProgressDialogSingleton {
  static ProgressDialogSingleton instance;
  ProgressDialog progressDialog;

  ProgressDialogSingleton(BuildContext context) {
    if (progressDialog == null) {
      progressDialog = new ProgressDialog(context);
      progressDialog.style(
        insetAnimCurve: Curves.easeInOut,
        backgroundColor: Colors.white,
        borderRadius: 10.0,
        progressWidget: Container(
            padding: EdgeInsets.all(8.0),
            child: Theme(
              data: ThemeData(
                accentColor: AllColors.primary
              ),
              child: CircularProgressIndicator(),
            )),
      );
    }
  }

  static  getInstance(BuildContext context) {
    if (instance == null) {
      instance = new ProgressDialogSingleton(context);
    }
    return  instance;
  }

  Future<void> showHide() async {
     try {
       if(progressDialog.isShowing()){
         await progressDialog.hide();
       }else{
         await progressDialog.show();
       }
     } catch (e) {
       print(e.toString());
     }
  }

  void onDispose(){
    instance = null;
    progressDialog = null;
  }

 
}