Flutter WebView with LocalStorage
Flutter WebView is used to embed web content within a Flutter application. It allows you to load web pages, run JavaScript code, and interact with the web content. LocalStorage is a web storage mechanism provided by browsers to store key-value pairs locally on the user’s device.
1. Adding Dependencies
To use WebView and LocalStorage in your Flutter project, you need to add the following dependencies to your pubspec.yaml
file:
dependencies:
flutter_webview_plugin: ^0.4.0
shared_preferences: ^2.0.10
2. Loading WebView
First, import the necessary packages:
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
Then, create an instance of the WebView plugin:
final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
3. Enabling LocalStorage
Before loading any web page, you need to enable LocalStorage in the WebView instance. You can do this by executing JavaScript code using the plugin:
flutterWebviewPlugin.evalJavascript(
"localStorage.setItem('key', 'value');"
);
4. Accessing LocalStorage
To access LocalStorage data from the web page loaded in WebView, you can use JavaScript again:
flutterWebviewPlugin.onStateChanged.listen((state) async {
if (state.type == WebViewState.finishLoad) {
String value = await flutterWebviewPlugin.evalJavascript(
"localStorage.getItem('key');"
);
print("LocalStorage value: $value");
}
});
5. Example
Here is a complete example of using WebView with LocalStorage in Flutter:
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
@override
Widget build(BuildContext context) {
// Enable LocalStorage
flutterWebviewPlugin.evalJavascript(
"localStorage.setItem('key', 'value');"
);
// Access LocalStorage
flutterWebviewPlugin.onStateChanged.listen((state) async {
if (state.type == WebViewState.finishLoad) {
String value = await flutterWebviewPlugin.evalJavascript(
"localStorage.getItem('key');"
);
print("LocalStorage value: $value");
}
});
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('WebView with LocalStorage'),
),
body: WebviewScaffold(
url: 'https://example.com',
withLocalStorage: true,
hidden: true,
initialChild: Center(
child: CircularProgressIndicator(),
),
),
),
);
}
}
In this example, we enable LocalStorage by setting a key-value pair with localStorage.setItem('key', 'value');
. Then, using the onStateChanged
event, we access the value using localStorage.getItem('key');
and print it to the console.
Also, notice that we set withLocalStorage: true
in the WebviewScaffold
widget to enable LocalStorage for the loaded web page.