How to Add Raw HTML in Flutter Webview

Even though using raw html inside 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 to load raw html.

Before starting, please do check out my previous blog posts 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 plugin dependency on your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  webview_flutter: 1.0.1

The value, that is the html code, for initialUrl attribute can be passed as below.

        WebView(
        initialUrl: new Uri.dataFromString('<html><body>hello world</body></html>',    mimeType: 'text/html').toString(),
        javascriptMode: JavascriptMode.unrestricted,
        )

Following is the complete webview raw html in flutter example.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';


void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Webview raw HTML Example',
      home: WebviewExample(),
    );
  }
}

class WebviewExample extends StatefulWidget {
  WebviewExample({Key key}) : super(key: key);

  @override
  _WebviewExampleState createState() => _WebviewExampleState();
}

class _WebviewExampleState extends State<WebviewExample> {


  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
        title: Text('Webview with raw HTML')),
      body: Container(
      child: WebView(
        initialUrl: new Uri.dataFromString('<html><body>hello world</body></html>', mimeType: 'text/html').toString(),
        javascriptMode: JavascriptMode.unrestricted,
        ),)
  );
  }
}

Following is the output of the tutorial.

Leave a Comment

Your email address will not be published. Required fields are marked *