I am trying to load a local HTML file in my WebViewScaffold
however I don't have a callback for onWebViewCreated
that the plugin webview_flutter
offers. I cannot use that dependency because I want access to the state listeners of the webview's callbacks that webview_flutter
doesn't offer. Could anyone show me how to load a local file? This is my current implementation -
final Set<JavascriptChannel> jsChannels = [
JavascriptChannel(
name: 'Print',
onMessageReceived: (JavascriptMessage message) {
print(message.message);
}),
].toSet();
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final flutterWebViewPlugin = FlutterWebviewPlugin();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter WebView Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: {
'/': (_) => const MyHomePage(),
'/widget': (_) {
return WebviewScaffold(
url: selectedUrl, // How to load a local file here?
javascriptChannels: jsChannels,
mediaPlaybackRequiresUserGesture: false,
appBar: AppBar(
title: const Text('Widget WebView'),
),
withZoom: true,
withLocalStorage: true,
hidden: true,
initialChild: Container(
color: Colors.redAccent,
child: const Center(
child: Text('Waiting.....'),
),
),
},
},
);
}
}
You can load a local HTML file from the user's phone like below:
...
url: Uri.dataFromString(
File('filePath').readAsStringSync(),
mimeType: 'text/html',
).toString(),
...
and if you want to open an html file from your app bundle(an html file in your assets folder), you can do it like this:
...
url: Uri.dataFromString(
await rootBundle.loadString('assets/index.html'),
mimeType: 'text/html',
).toString(),
...
Note: You have to declare the html file in your pubspec.yaml
assets section like any other asset.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments