Created
August 8, 2020 06:33
-
-
Save vignarajj/59a518610a2bfeb09ad4b0b6d8fe7c69 to your computer and use it in GitHub Desktop.
WebView Flutter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
import 'package:webview_flutter/webview_flutter.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
visualDensity: VisualDensity.adaptivePlatformDensity, | |
), | |
home: MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
WebViewController _webViewController; | |
String url = 'assets/sample.html'; | |
@override | |
void initState() { | |
super.initState(); | |
} | |
Future<void> _loadHtmlFromAssets(String filePath) async { | |
String fileHtmlContents = await rootBundle.loadString(filePath); | |
_webViewController.loadUrl(Uri.dataFromString(fileHtmlContents, | |
mimeType: 'text/html', encoding: Encoding.getByName('utf-8')) | |
.toString()); | |
} | |
@override | |
Widget build(BuildContext context) { | |
// This method is rerun every time setState is called, for instance as done | |
// by the _incrementCounter method above. | |
// | |
// The Flutter framework has been optimized to make rerunning build methods | |
// fast, so that you can just rebuild anything that needs updating rather | |
// than having to individually change instances of widgets. | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: SafeArea( | |
child: WebView( | |
initialUrl: '', | |
javascriptMode: JavascriptMode.unrestricted, | |
onWebViewCreated: (WebViewController webViewController) async { | |
_webViewController = webViewController; | |
await _loadHtmlFromAssets(url); | |
}), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment