Flutter包资源和http请求
Posted 码上加油站
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter包资源和http请求相关的知识,希望对你有一定的参考价值。
说明
Flutter Java 语言里的 jar 包,由 全球众多开发者共同提供第三方库 例如, 网络请求)、自定义导航/路由处理 及第三方平台 SDK 等 ,这使得开发者可以快速构建应用程序,
示例
首先去包资源网站,搜索你所需包依赖:
打开项目目录下的pubspec.yaml文件,添加包资源依赖:
使用示例:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() => runApp(MyApp());
//MyApp不需要做状态处理,所以此组件继承StatelessWidget即可
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//此组件是整个应用的主组件
return new MaterialApp(
title: '使用包资源示例',
home: new Scaffold(
appBar: new AppBar(
title: new Text('使用包资源示例'),
),
body: new Center(
child: new RaisedButton(
onPressed: () {
//指定url并发起请求
const url = 'https://www.baidu.com';
launch(url);
},
child: new Text('打开百度'),
),
),
),
);
}
}
说明
官方使用的是用dart:io中的HttpClient发起的请求,但HttpClient本身功能较弱,很多常用功能都不支持。建议使用dio来发起网络请求,它是一个强大易用的darthttp请求库,支持RestfulAPI、FormData、拦截器、请求取消、Cookie管理、文件上传/下载等等,详情可去包资源网站搜dio。
示例
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
void main() {
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> {
var _ipAddress = 'Unknown';
_getIPAddress() async {
var url = 'https://httpbin.org/ip';
var httpClient = new HttpClient();
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(utf8.decoder).join();
var data = jsonDecode(json);
result = data['origin'];
} else {
result =
'Error getting IP address:\nHttp status ${response.statusCode}';
}
} catch (exception) {
result = 'Failed getting IP address';
}
// If the widget was removed from the tree while the message was in flight,
// we want to discard the reply rather than calling setState to update our
// non-existent appearance.
if (!mounted) return;
setState(() {
_ipAddress = result;
});
}
@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('Your current IP address is:'),
new Text('$_ipAddress.'),
spacer,
new RaisedButton(
onPressed: _getIPAddress,
child: new Text('Get IP address'),
),
],
),
),
);
}
}
完
码上加油站
一起来加油
长按扫码关注
点“在看”你懂得
以上是关于Flutter包资源和http请求的主要内容,如果未能解决你的问题,请参考以下文章
Flutter 报错 DioError [DioErrorType.DEFAULT]: Bad state: Insecure HTTP is not allowed by platform(代码片段
带有firebase的Flutter HTTP包不适用于删除请求,但适用于发布,补丁和获取?