반응형
플러터 소스
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() { runApp(MyApp()); }
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData( primarySwatch: Colors.blue, ),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late WebViewController _webViewController;
@override Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar( title: Text('웹뷰'), ),
body: WebView(
initialUrl: 'http:mywebaddress',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_webViewController = webViewController;
},
javascriptChannels: Set.from([
JavascriptChannel(
name: "colorChanged",
onMessageReceived: (JavascriptMessage result) {
print("받은 메시지 : $result"); }),
JavascriptChannel(
name: "webToAppChange",
onMessageReceived: (JavascriptMessage result) {
print("webToAppChange 메시지 : $result");
_webViewController.evaluateJavascript('appToWeb("red")');
}),
]),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
_webViewController.evaluateJavascript('appToWeb("black")');
},
),
);
}
}
html 소스
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<html>
<head>
<title>Sample page</title>
<script>
function changeColor() {
var colors = ["black","red","green"];
var randonNumber = Math.floor(Math.random() * 3);
var myDiv = document.getElementById("container_box");
myDiv.style.backgroundColor = colors[randonNumber];
try { colorChanged.postMessage(colors[randonNumber]); } catch (err) { }
}
function webToApp(msg) {
alert(msg);
try { webToAppChange.postMessage(msg); } catch (err) { }
}
function appToWeb(color) {
alert("aa");
var myDiv = document.getElementById("container_box");
myDiv.style.backgroundColor = color;
}
</script>
<style type="text/css">
#btn_color {
display: block;
margin: auto;
}
#container_box {
height: 500px;
width: 150px;
border: 1px solid #000;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="container_box"></div> <br>
<button id="btn_color" onclick="changeColor()"> Change Color</button>
<button id="btn_webToApp" onclick="webToApp('웹페이지에서 앱 전달')">webToApp</button>
<button id="btn_appToWeb" onclick="appToWeb('black')">appToWeb</button>
</body>
</html>
'flutter.widget' 카테고리의 다른 글
FractionallySizedBox (0) | 2021.04.06 |
---|---|
image (0) | 2020.11.30 |
DropdownButton (0) | 2020.11.13 |
Builder (0) | 2019.11.27 |
[내용추가 필요]PageView (0) | 2019.11.25 |