Search code examples
flutterdarturldialogwhatsapp

Flutter: whatsApp uri link opens without showing the Flutter Dialog


I have an application where I share records through WhatsApp messages. The issue I am facing is that I have a Dialog in place where I ask the user if the user wants to share the record. My application does not show the Dialog and launches the WhatsApp application directly. I am not able to understand why it is happening. Without the WhatsApp launch function, the Dialog gets displayed, but with the function in place, the Dialog does not show.

My dialog

void whatsAppDialog(
    {required BuildContext context, required Function onPressed}) {
  if (Platform.isIOS) {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: const Text('Share Record'),
            content: const Text('Do you want to share this record?'),
            actions: [
              CupertinoDialogAction(
                child: const Text('Cancel'),
                onPressed: () => Navigator.pop(context),
              ),
              CupertinoDialogAction(
                onPressed: onPressed(),
                child: const Text('Share'),
              ),
            ],
          );
        });
  } else {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: const Text('Share Record'),
            content: const Text('Do you want share this record?'),
            actions: [
              TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('Cancel')),
              TextButton(onPressed: onPressed(), child: const Text('Share'))
            ],
          );
        });
  }
}

My WhatsApp launch function.

launchWhatsApp({
    String? studentName,
    String? mobileNumber,
    List<Records>? savedRecords,
    double? avgGrade,
    String? date,
    String? remarks,
  }) async {
    // Initialize the message with student name and average grade
    String message =
        'Date: $formattedDate\n\nStudent Name: $studentName\n\nAverage Grade: $avgGrade\n\nRemarks: $remarks\n\n';

    // Iterate through each saved record and add its details to the message
    if (savedRecords != null && savedRecords.isNotEmpty) {
      for (int i = 0; i < savedRecords.length; i++) {
        Records record = savedRecords[i];
        message += 'Record ${i + 1}:\n';
        message += 'Juz: ${record.juz}\n';
        message += 'Surah: ${record.surah}\n';
        message += 'Page: ${record.page ?? '-'}\n'; // Handle null page
        message += 'Ayat: ${record.ayat ?? '-'}\n'; // Handle null ayat
        message += 'Grade: ${record.grade}\n\n';
      }
    }

    // Create the WhatsApp link with the composed message
    final link = WhatsAppUnilink(
      phoneNumber: mobileNumber,
      text: message,
    );

    // Launch the WhatsApp link
    await launchUrl(link.asUri());
  }  

My Button where I am saving record to firebase database then launching the dialog.

onPressed: () {
                    context.read<MurajaatRecordCubit>().saveRecordsToFirestore(
                        studentModel,
                        remarks: remarksController.text.isEmpty
                            ? 'no remarks'
                            : remarksController.text)
                    .then(
                          (value) => Future.delayed(
                            const Duration(seconds: 3),
                            () => whatsAppDialog(
                                onPressed: () => launchWhatsApp(
                                    mobileNumber: studentModel.mobileNumber,
                                    studentName:
                                        '${studentModel.studentName} ${studentModel.fatherName} ${studentModel.surname}\n',
                                    savedRecords: murajaatState.savedRecords,
                                    avgGrade: murajaatState.avgGrade,
                                    remarks: remarksController.text),
                                context: context),
                          ),
                        );  

I am using whatsapp_unilink package and url_launcher package. I am want to show the Dialog and then user gets to choose whether to share the record or not.


Solution

  • The issue you're facing seems to be related to how you're handling the onPressed function in your whatsAppDialog function.

    CupertinoDialogAction( onPressed: onPressed(), // Issue here child: const Text('Share'), ),

    Here, you're immediately invoking the onPressed function instead of passing a reference to it. As a result, the function is called as soon as the dialog is built, not when the user taps the "Share" button. To fix this issue, you should pass a reference to the onPressed function without invoking it immediately. Modify your CupertinoDialogAction and TextButton like this:

    CupertinoDialogAction( onPressed: onPressed, // Pass a reference to onPressed child: const Text('Share'), ),

    TextButton( onPressed: onPressed, // Pass a reference to onPressed child: const Text('Share') )

    By passing the reference to the onPressed function without invoking it, the function will only be called when the user taps the "Share" button in the dialog.

    Make sure to apply this change in both the iOS and non-iOS branches of your whatsAppDialog function. This should resolve the issue and ensure that the dialog is displayed properly before launching the WhatsApp application.