When building mobile apps, sometimes you need to display web content directly inside your app. Whether it’s your privacy policy, terms of service, or an external webpage, Flutter makes this possible through the WebView widget. In this article, we’ll walk through the basics of displaying a webpage inside a Flutter app using the webview_flutter
package.
●Related Articles
- Adding Back and Forward Buttons in Flutter WebView
- Handling File Uploads and PDF Viewing in Flutter WebView
1. Adding the webview_flutter Package
To begin, add the following dependency to your pubspec.yaml
file:
dependencies:
webview_flutter: ^4.2.2
Then run flutter pub get
to install the package.
2. Setting Up WebView in Your Widget
Here’s a basic example of how to embed a WebView:
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
final controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(Uri.parse('https://example.com'));
return Scaffold(
appBar: AppBar(
title: Text('WebView Example'),
),
body: WebViewWidget(controller: controller),
);
}
}
3. Enabling JavaScript
In the code above, we used setJavaScriptMode(JavaScriptMode.unrestricted)
to allow JavaScript execution in the WebView. This is useful if the webpage requires it for functionality.
4. Android and iOS Permissions
Don’t forget platform-specific configurations:
For Android:
- Make sure your
AndroidManifest.xml
includes Internet permission:
<uses-permission android:name="android.permission.INTERNET"/>
For iOS:
- Ensure you set
NSAppTransportSecurity
properly inInfo.plist
if you’re loading insecure (HTTP) URLs.
Conclusion
Using WebView in Flutter is straightforward and powerful. With just a few lines of code, you can seamlessly integrate web pages into your app. In future posts, we’ll dive deeper into WebView navigation controls, file uploads, and handling links more dynamically.
Comment