How to Add Raw HTML in Flutter Webview
Even though using raw HTML inside the mobile app is not usual, you may need it for some specific actions. In this flutter tutorial, let’s check out how to make the flutter webview load raw HTML.
Before starting, please check out my previous tutorials on Flutter webview- how to add webview in flutter and how to create a webview with progress indicator.
So, let’s see how to add raw Html in the webview. First of all, ensure to add webview flutter using the following command.
flutter pub add webview_flutter
You can load the HTML to the WebViewController as given below.
WebViewController()
..loadRequest(
Uri.dataFromString(
'''<html><head><title>Href Attribute Example</title></head><body><h1>Href Attribute Example</h1>
<p><a href="https://www.freecodecamp.org/contribute/">The freeCodeCamp Contribution Page</a>
shows you how and where you can contribute to freeCodeCamp community and growth.</p></body></html>''',
mimeType: 'text/html', encoding: Encoding.getByName('utf-8')),
);
Following is the complete webview raw HTML in Flutter example.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
useMaterial3: true,
),
home: const MyStatefulWidget());
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
late final WebViewController controller;
var loadingPercentage = 0;
@override
void initState() {
super.initState();
controller = WebViewController()
..setNavigationDelegate(NavigationDelegate(
onPageStarted: (url) {
setState(() {
loadingPercentage = 0;
});
},
onProgress: (progress) {
setState(() {
loadingPercentage = progress;
});
},
onPageFinished: (url) {
setState(() {
loadingPercentage = 100;
});
},
))
..loadRequest(
Uri.dataFromString(
'''<html><head><title>Href Attribute Example</title></head><body><h1>Href Attribute Example</h1>
<p><a href="https://www.freecodecamp.org/contribute/">The freeCodeCamp Contribution Page</a>
shows you how and where you can contribute to freeCodeCamp community and growth.</p></body></html>''',
mimeType: 'text/html', encoding: Encoding.getByName('utf-8')),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView Example'),
),
body: Stack(
children: [
WebViewWidget(
controller: controller,
),
if (loadingPercentage < 100)
LinearProgressIndicator(
value: loadingPercentage / 100.0,
),
],
));
}
}
Following is the output of the tutorial.
That’s how you load HTML through webview in Flutter.