URLs in Flutter

Flutter provides many screens with different components, or we can set them on the screen, components like buttons, text, etc. We can perfect the event to open the URL on browse so pass the URL in the browse like open website, etc.

  • In browser(default)
  • In-App

When it comes to opening a website in a browser, then two applications are required for work: One app user and another app. 


The steps for adding the plugin to the Flutter application:


Step 1: Create a new project in the Flutter mobile application or you can use an already created Flutter project.  


Step 2: Open the “pubspec. yaml” file of the project. 


Step 3: Add the below line “pubspec. yaml” file on the project.

Dependencies:

   Flutter:

     sdk: flutter

     url_launcher:

Step 4: Now click the “Pub Get” button in the top right corner.


Step 5: After “Pub Get” clicked.


Step 6: Let’s success about example of URL flutter


Step 6.1: Syntax to load URL Flutter is the most important part of passing URL using await launch open the browser. 

_launchURL() async {

const url = 'https://www.candidroot.com/';

if (await launch(url)) {

await canLaunch(url);

} else {

throw 'Could not launch $url';

}

}

Step 6.2: Create a main. dart in the lib folder.

import 'package:flutter/material.dart';

import 'package:url_launcher/url_launcher.dart';

// function to trigger the build process

void main() => runApp(const MyApp());

_launchURL() async {

const url = 'https://www.candidroot.com/';

if (await launch(url)) {

await canLaunch(url);

} else {

throw 'Could not launch $url';

}

}

class MyApp extends StatelessWidget {

const MyApp({Key? key}) : super(key: key);

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold(

appBar: AppBar(

title: const Text('Candidroot solution'),

backgroundColor: Colors.blue,

),

body: SafeArea(

child: Center(

child: Column(

children: [

Container(

height: 250.0,

),

const Text(

'Welcome to Candidroot solution!',

style: TextStyle(

fontSize: 20.0,

color: Colors.blue,

fontWeight: FontWeight.bold,

),

),

Container(

height: 20.0,

),

ElevatedButton(

onPressed: _launchURL,

style: ButtonStyle(

padding:

MaterialStateProperty.all(const EdgeInsets.all(5.0)),

textStyle: MaterialStateProperty.all(

const TextStyle(color: Colors.black),

),

),

// textColor: Colors.black,

// padding: const EdgeInsets.all(5.0),

child: const Text('Open in Browser'),

),

Container(

height: 20.0,

),

ElevatedButton(

onPressed: _launchURL,

style: ButtonStyle(

padding:

MaterialStateProperty.all(const EdgeInsets.all(5)),

textStyle: MaterialStateProperty.all(

const TextStyle(color: Colors.black))),

// textColor: Colors.black,

// padding: const EdgeInsets.all(5.0),

child: const Text('Open in App'),),],),),),),);}}

Step 7: Output of above code.


Happy coding!

365Bloggy May 13, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive