It'sPhil
It'sPhil

Reputation: 117

Open app when button is clicked I want to open the Gmail app when I click the button. I am using the url launcher

I want to open the Gmail app when I click the button. I am using the url launcher.

         `InkWell(
          child: Row(mainAxisSize: MainAxisSize.min, children: const [
            SizedBox(
              width: 30.0,
              height: 60.0,
            ),
            Text(' "/Open Email/" ',
                style: TextStyle(
                  color: Colors.black,
                )),
          ]),
          onTap: () {
            const url = 'https://mail.google.com/mail/u/0/#inbox';
            launchURL(url);
          }),`

When I click this its open the web instead of the app

Upvotes: 2

Views: 4451

Answers (5)

Rustam Usmanov
Rustam Usmanov

Reputation: 312

You can use this code in your native code without using any packages:

in MainActivity.kt

package com.example.you_app

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.graphics.Color
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
    private val CHANNEL = "com.example.you_app"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.statusBarColor = Color.WHITE
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
            .setMethodCallHandler { call, result ->
                if (call.method == "openGmail") {
                    val success = openGmailApp()
                    if (success) {
                        result.success(null)
                    } else {
                        result.error("GMAIL_NOT_FOUND", "Gmail app is not installed", null)
                    }
                } else {
                    result.notImplemented()
                }
            }
    }

    private fun openGmailApp(): Boolean {
        return try {
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_APP_EMAIL)
            startActivity(intent)
            true
        } catch (anfe: android.content.ActivityNotFoundException) {
            false
        }
    }
}

in your Flutter code :

class EmailVerificationPage extends StatelessWidget {
  const EmailVerificationPage({super.key});
  static const _platform = MethodChannel('com.example.you_app');

  Future<void> _openMailApp() async {
    try {
      await _platform.invokeMethod('openGmail');
    } on PlatformException catch (e) {
      debugPrint("Failed to open mail app: ${e.message}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return YourButton(
       title: "OPEN EMAIL APP",
       backgroundColor: CustomColors.primaryRed,
       onPressed: _openMailApp,
    );
  }
}

Upvotes: 0

Koofng
Koofng

Reputation: 202

Using Andriod_intent_plus for Android and url_launcher for iOS you can achieve this.

if (Platform.isAndroid) {
   final AndroidIntent intent = AndroidIntent(
           action: 'android.intent.action.MAIN',
           category: 'android.intent.category.APP_EMAIL',
  );
  
  intent.launch().catchError((e) {});
} else if (Platform.isIOS) {
  launch('message://').catchError((e) {});
}

Upvotes: 2

Arif Akram
Arif Akram

Reputation: 98

A utils class for sending email, this class can be used for opening whats app, call, message, etc.

import 'package:url_launcher/url_launcher.dart' as UL;

class Utils {
  static Future<void> sendEmail(
      {String email, String subject = "", String body = ""}) async {
    String mail = "mailto:$email?subject=$subject&body=${Uri.encodeFull(body)}";
    if (await UL.canLaunch(mail)) {
      await UL.launch(mail);
    } else {
      throw Exception("Unable to open the email");
    }
  }
}

Call the method from any class with a click of a button.

import 'utils.dart';

void onOpenMailClicked() async {
  try {
       await Utils.sendEmail(
       email: "[email protected]",
       subject: "Optional",
       );
       } catch (e) {
        debugPrint("sendEmail failed ${e}");
       }
}

You need to provide queries for android on the manifest file.

<manifest 
  xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.example">
       
  <queries>
    <intent>
      <action android:name="android.intent.action.SEND" />
      <data android:mimeType="image/jpeg" />
      </intent>
  </queries>
   <application .............

Upvotes: 1

manhtuan21
manhtuan21

Reputation: 3430

you should change

const url = 'https://mail.google.com/mail/u/0/#inbox';

to

const url = 'mailto:${your_receiver_email}';

Upvotes: 1

M Karimi
M Karimi

Reputation: 3493

Uri gmailUrl = Uri.parse('mailto:[email protected]?subject=Greetings&body=Hello%20World');

InkWell(
          child: Row(mainAxisSize: MainAxisSize.min, children: const [
            SizedBox(
              width: 30.0,
              height: 60.0,
            ),
            Text(' "/Open Email/" ',
                style: TextStyle(
                  color: Colors.black,
                )),
          ]),
          onTap: () {
            _launch(gmailUrl);
          }),

and it’s _launch function:

    Future<void> _launch(Uri url) async {
    await canLaunchUrl(url)
        ? await launchUrl(url)
        : _showSnackBar('could_not_launch_this_app'.tr());
      }

Upvotes: 0

Related Questions