Skip to content

Commit

Permalink
🌱 flutter 与 webview 通信
Browse files Browse the repository at this point in the history
  • Loading branch information
BTMuli committed Aug 13, 2024
1 parent 761e15e commit 9afdb0e
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 5 deletions.
51 changes: 51 additions & 0 deletions assets/lib/test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.alert {
padding: 20px;
background-color: #f44336;
color: white;
}

.closebtn {
margin-left: 15px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
line-height: 20px;
cursor: pointer;
transition: 0.3s;
}

.closebtn:hover {
color: black;
}
</style>
<script>
// SEND DATA TO FLUTTER
function sendDataToFlutter() {
var value = {"name":"tashi"}
window.chrome.webview.postMessage(value);
}
// LISTEN DATA FROM FLUTTER
window.chrome.webview.addEventListener('message', function(e) {
alert("messagereceived: " + JSON.stringify(e.data));
});
</script>
</head>
<body>
<h2>Alert Messages</h2>

<p>Click on the "x" symbol to close the alert message.</p>
<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
<strong>Danger!</strong> Indicates a dangerous or potentially negative action.
</div>
<p>Click the button to display an alert box.</p>

<button onclick="sendDataToFlutter()">Send JSON Data to flutter</button>
</body>
</html>
14 changes: 9 additions & 5 deletions lib/pages/main/app_dev.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// Project imports:
import '../../tools/file_tool.dart';
import '../../tools/log_tool.dart';
import '../../ui/sp_webview.dart';

/// 测试页面
Expand All @@ -21,12 +23,14 @@ class _AppDevPageState extends ConsumerState<AppDevPage> {
/// 创建新窗口
Future<void> createNewWindow() async {
if (!mounted) return;
controller = await SpWebview.createWebview(
context,
'https://www.baidu.com',
);
var fileTool = SPFileTool();
var filePath = await fileTool.getAssetsPath('lib/test.html');
if (!mounted) return;
await controller!.show(context);
controller = await SpWebview.createWebview(context, filePath);
controller!.listen('message', callback: (event) {
SPLogTool.info('[Webview] Receive message: $event');
});
if (mounted) await controller!.show(context);
}

/// 构建函数
Expand Down
12 changes: 12 additions & 0 deletions lib/tools/file_tool.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ class SPFileTool {
return path.join(dir, relativePath);
}

/// 获取assets目录下的文件路径
Future<String> getAssetsPath(String relativePath) async {
var assetsPath = path.join(
path.dirname(Platform.resolvedExecutable),
'data',
'flutter_assets',
'assets',
relativePath,
);
return Uri.file(assetsPath).toString();
}

/// 检测文件是否存在
Future<bool> isFileExist(String path) async {
return File(path).exists();
Expand Down
14 changes: 14 additions & 0 deletions lib/ui/sp_webview.dart
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@ class SpWebviewController extends ChangeNotifier {
icon: const Icon(FluentIcons.chrome_close),
onPressed: () => Navigator.pop(context),
),
IconButton(
icon: const Icon(FluentIcons.chrome_restore),
onPressed: () async {
var data = '{"message": "Hello, Flutter!"}';
await webview.postWebMessage(data);
},
)
],
),
constraints: BoxConstraints(
Expand All @@ -118,6 +125,13 @@ class SpWebviewController extends ChangeNotifier {
webview.dispose();
notifyListeners();
}

void listen(String event, {Function(dynamic)? callback}) {
webview.webMessage.listen((event) {
if (event == null) return;
if (callback != null) callback(event);
});
}
}

class SpWebview extends StatefulWidget {
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ flutter:
assets:
- assets/fonts/
- assets/images/
- assets/lib/
- assets/schema/

# An image asset can refer to one or more resolution-specific "variants", see
Expand Down

0 comments on commit 9afdb0e

Please sign in to comment.