初學flutter,初學前端,嘗試在dart中直接使用HttpClient時,直接報出Platform not supported,查資料發現他還不支持瀏覽器。 通過查閱資料發現可以借助axios 與 dart:js 之間的互相調用來實現。目前還不清楚有沒有其它更好的方式。實例代碼:
main.dart:
import 'package:flutter/material.dart';
import 'dart:js';
void callJS(){
context['console'].callMethod('log', ['開始調用']);
JsObject(context['getDartCall'], ['http://*****.com','{ID: 1234 , Name: "Hunter"}']);
}
void jsCallBack(resData){
//結果回調
print(resData);
}
void main() {
//定義回調方法
context['jsCallBack'] = jsCallBack;
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var spacer = new SizedBox(height: 32.0);
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('Dart 與 JS 互相調用實例'),
new Text('發起調用'),
spacer,
new RaisedButton(
onPressed: (){
callJS();
},
child: new Text('發起調用'),
),
],
),
),
);
}
}
在web下的index.html里面需要引入對應的js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="sharebook">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="shortcut icon" type="image/png" href="favicon.png"/>
<title>sharebook</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js" type="application/javascript"></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
function getDartCall(reqUrl, arg){
resResult = '';
axios({
method: 'get',
url: reqUrl,
params: arg
})
.then(function(response) {
resResult = response.data;
jsCallBack(resResult);
}).catch(function(erroe){
//請求失敗回調
jsCallBack(erroe);
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
