2 min readNov 6, 2022
WebView in Flutter
Hi today let see how to implement WebView in Flutter with short lines of code. So first that we need to get the latest WebView version to get it added in the pubspec.yaml for that we can get from pub dev site which i pasted below
so you can copy the version from there and you can paste it directly in pubspec.yaml under dependencies as below
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
webview_flutter: ^3.0.4
Let Quickly jump in to the coding part so i have created a file named ReadContentPage.dart
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class ReadContentPage extends StatefulWidget {
String url;
ReadContentPage(this.url);
@override
State<ReadContentPage> createState() => _ReadContentPageState(url);
}
class _ReadContentPageState extends State<ReadContentPage> {
String url;
_ReadContentPageState(this.url);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("WebView Page",
style: const TextStyle(fontStyle: FontStyle.italic,
fontSize: 20, color: Colors.white)
),
actions: [
IconButton(
onPressed: () {},
icon: Icon(Icons.favorite_border)
)
],
),
body: WebView(
initialUrl: url,
javascriptMode: JavascriptMode.unrestricted,
));
}
}
And we can call it from main.dart as
import 'package:flutter/material.dart';
import 'ReadContentPage.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const ReadContentPage("https://google.com"),
);
}
}
Final output will be