flutter version: 2.10.1
dart version: 2.16.1
webview_flutter version: ^3.0.0
网上看到别人使用的js都是直接写在
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>BBBBBBBBBBBB</h1>
<button onclick="setname('hsw')">设置名称</button>
</body>
</html>
function setname(name) {
console.log("my name is " + name);
}
可以现在项目根目录下面创建一个文件夹 assets
flutter:
assets:
- assets/html/
注意前面的空格!!!
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter/services.dart' show rootBundle;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late WebViewController _webViewController;
String filePath = 'assets/html/index.html';
String jsPath = 'assets/html/script.js';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: WebView(
initialUrl: '',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_webViewController = webViewController;
_loadHtmlFromAssets();
},
onPageFinished: (url) async {
//加载js文件
String jsContent = await rootBundle.loadString(jsPath);
_webViewController.runJavascript(jsContent);
//加载js脚本 _webViewController.runJavascriptReturningResult("setname('hsw')").then((value) => {
print(value)
});
},
),
);
}
_loadHtmlFromAssets() async {
String fileHtmlContent = await rootBundle.loadString(filePath);
_webViewController.loadHtmlString(fileHtmlContent);
String jsContent = await rootBundle.loadString(jsPath);
_webViewController.runJavascript(jsContent);
}
}