flutter-web利用dart js 库发起http request
初学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>