For the image files, you can convert it to base64
to display the image. Here I use a simple version of html
for demonstration purpose:
var htmlString = '''
<html>
<head><title>Test WebView</title></head>
<body>{}</body>
</html>
''';
var image = await http.get(url); // Download the image
// Insert in the base64 String
var htmlString = htmlString.replaceFirst('{}',
'<img src=data:image/jpeg;base64,${base64Encode(image.bodyBytes)}>');
_controller.loadUrl(
Uri.dataFromString(htmlString, mimeType: 'text/html').toString());
For the pdf, it's best to use the package flutter_cached_pdfview that's both easy to use for local or online file. Another quick way is to use the embedded view from google docs:
var displayUrl = 'https://docs.google.com/gview?embedded=true&url=$url';
Full example code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:http/http.dart' as http;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MaterialApp(home: HelpScreen()));
}
class HelpScreen extends StatefulWidget {
@override
HelpScreenState createState() => HelpScreenState();
}
class HelpScreenState extends State<HelpScreen> {
WebViewController _controller;
var pdfUrl = 'www.africau.edu/images/default/sample.pdf';
var imageUrl =
'https://file-examples-com.github.io/uploads/2017/10/file_example_PNG_500kB.png';
var htmlString = '''
<html>
<head><title>Test WebView</title>
</head>
<body>
{}
</body>
</html>
''';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Help')),
body: WebView(
initialUrl: 'about:blank',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
_loadHtmlFromAssets(imageUrl);
_loadHtmlFromAssets(pdfUrl);
},
),
);
}
_loadHtmlFromAssets(String url) async {
if (url.contains('png') || url.contains('jpg')) {
var image = await http.get(url); // Download the image
htmlString = htmlString.replaceFirst('{}',
'<img src=data:image/jpeg;base64,${base64Encode(image.bodyBytes)}>');
_controller.loadUrl(
Uri.dataFromString(htmlString, mimeType: 'text/html').toString());
} else if (url.contains('pdf')) {
var displayUrl = 'https://docs.google.com/gview?embedded=true&url=$url';
_controller.loadUrl(displayUrl).toString();
}
}
}