Written by: Manish Methani
June 19, 2024 at 5:06pm IST.
Ensure you have Flutter installed on your machine. If not, follow the installation guide on the official Flutter website.
Open your terminal or command prompt, navigate to your desired directory, and create a new Flutter project:
flutter create url_launcher_demo
Navigate into your project directory:
cd url_launcher_demo
url_launcher
DependencyOpen the pubspec.yaml
file in your Flutter project and add the url_launcher
dependency:
dependencies: flutter: sdk: flutter url_launcher: ^6.3.0
Run flutter pub get
to install the new dependency:
flutter pub get
Open the lib/main.dart
file and replace its contents with the following code:
import "package:flutter/material.dart"; import "package:url_launcher/url_launcher.dart"; void main() { runApp(UrlLauncherDemo()); } class UrlLauncherDemo extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Flutter URL Launcher Demo"), ), body: Center( child: ElevatedButton( onPressed: _launchURL, child: Text("Open YouTube Video"), ), ), ), ); } Future_launchUrl() async { final Uri _url = Uri.parse("https://www.youtube.com/watch?v=-GSO9cIMp5Y"); // Replace with your YouTube video URL if (!await launchUrl(_url)) { throw Exception("Could not launch $_url"); } } }
For Android, you need to ensure that you have the appropriate permissions. Open android/app/src/main/AndroidManifest.xml
and ensure it contains the following permissions within the <manifest>
tag:
<uses-permission android:name="android.permission.INTERNET"/>
For iOS, you need to update the Info.plist
file. Open ios/Runner/Info.plist
and add the following lines inside the <dict>
tag:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
Now that everything is set up, you can run your app using the following command:
flutter run
This will start the app on an available emulator or connected device.
Scaffold
with an AppBar
and a Center
ed ElevatedButton
.url_launcher
package to launch the specified URL in the default web browser.UrlLauncherDemo
widget.You have now created a simple Flutter app that opens a YouTube video using the url_launcher
package. By following these steps, you can easily extend this functionality to open other URLs or handle other types of links within your Flutter applications.