In Flutter, you can initiate a phone call by using the url_launcher
package. This package allows you to open URLs, including phone numbers, in the device’s default application, which is typically the phone app for phone numbers. Here’s how you can call a phone number in Flutter:
Step 1: Add the Dependency
First, add the url_launcher
dependency to your pubspec.yaml
file:
dependencies: flutter: sdk: flutter url_launcher: ^6.0.3
Then, run flutter pub get
to fetch the package.
Step 2: Import the Package
In your Dart code, import the url_launcher
package:
import 'package:url_launcher/url_launcher.dart';
Step 3: Implement the Phone Call Function
You can create a function to make a phone call using the launch
method from the url_launcher
package. Here’s an example:
void makePhoneCall(String phoneNumber) async { final Uri _phoneLaunchUri = Uri(scheme: 'tel', path: phoneNumber); if (await canLaunch(_phoneLaunchUri.toString())) { await launch(_phoneLaunchUri.toString()); } else { throw 'Could not launch $_phoneLaunchUri'; } }
In this example, the makePhoneCall
function takes a phone number as a parameter, creates a tel
URI, checks if the device is capable of launching the URI, and then calls launch
to open the phone app with the specified phone number.
Step 4: Use the Function to Make a Call
You can now use the makePhoneCall
function to make a phone call. For example, you might have a button that triggers the call:
ElevatedButton( onPressed: () { makePhoneCall('123-456-7890'); // Replace with the desired phone number }, child: Text('Call'), )
When the button is pressed, it will initiate a phone call to the specified phone number.
Remember to replace '123-456-7890'
with the actual phone number you want to call.
Step 5: Request Permissions (Optional)
In some cases, you might need to request permission to make phone calls. If your app targets Android API level 30 or higher, you’ll need to add the CALL_PHONE
permission to your AndroidManifest.xml file and request permission at runtime. On iOS, you don’t need to request permission to make phone calls.
That’s it! You’ve now implemented phone call functionality in your Flutter app using the url_launcher
package. Users can initiate a call by tapping the button or triggering the makePhoneCall
function programmatically.