热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Flutter配置网络

见图:1,添加的依赖关系,在pubspec.yaml文件里2,打开文件pubspec.yaml在环境下的第一个依赖里里里写

见图:

1,添加的依赖关系,在pubspec.yaml文件里

2,打开文件pubspec.yaml

在环境下的第一个依赖里里里写http:0.12.0,然后点击右上角的包得到,这样就会去下载http包

大约2秒就好了,这样的话我们的网络HTTP包就导入进来了,这样就可以访问网络了。

新建一个networkbackground.dart文件

导入以下代码

import 'dart:convert';import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:isolate';void main() {runApp(SampleApp());
}class SampleApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Sample App',theme: ThemeData(primarySwatch: Colors.blue,),home: SampleAppPage(),);}
}class SampleAppPage extends StatefulWidget {SampleAppPage({Key key}) : super(key: key);@override_SampleAppPageState createState() => _SampleAppPageState();
}class _SampleAppPageState extends State {List widgets = [];@overridevoid initState() {super.initState();loadData();}showLoadingDialog() {if (widgets.length == 0) {return true;}return false;}getBody() {if (showLoadingDialog()) {return getProgressDialog();} else {return getListView();}}getProgressDialog() {return Center(child: CircularProgressIndicator());}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("Sample App"),),body: getBody());}ListView getListView() => ListView.builder(itemCount: widgets.length,itemBuilder: (BuildContext context, int position) {return getRow(position);});Widget getRow(int i) {return Padding(padding: EdgeInsets.all(10.0), child: Text("Row ${widgets[i]["title"]}"));}loadData() async {ReceivePort receivePort = ReceivePort();await Isolate.spawn(dataLoader, receivePort.sendPort);// The 'echo' isolate sends its SendPort as the first messageSendPort sendPort = await receivePort.first;List msg = await sendReceive(sendPort, "https://jsonplaceholder.typicode.com/posts");setState(() {widgets = msg;});}// the entry point for the isolatestatic dataLoader(SendPort sendPort) async {// Open the ReceivePort for incoming messages.ReceivePort port = ReceivePort();// Notify any other isolates what port this isolate listens to.sendPort.send(port.sendPort);await for (var msg in port) {String data = msg[0];SendPort replyTo = msg[1];String dataURL = data;http.Response response = await http.get(dataURL);// Lots of JSON to parsereplyTo.send(json.decode(response.body));}}Future sendReceive(SendPort port, msg) {ReceivePort response = ReceivePort();port.send([msg, response.sendPort]);return response.first;}
}

3,点击运行,网络获取的数据就完成了


如果您没有导入http库的话,那么将'package:http / http.dart'作为http;会报错,找不到网络库。


如果你的http包引入的位置有错误的话,也会报这个错:这里不允许映射值。你早些时候错过了结肠吗?

集成HTTP库

https://pub.dartlang.org/packages/http
添加依赖
dependencies:http: ^0.12.0
安装
flutter packages get
导入
import 'package:http/http.dart' as http;

常用方法

get(dynamic url, { Map headers }) → Future

  • (必须)网址:请求地址
  • (可选)标头:请求头

post(dynamic url, { Map headers, dynamic body, Encoding encoding }) → Future

  • (必须)网址:请求地址
  • (可选)标头:请求头
  • (可选)体:参数
  • (编码)编码:编码例子

http.post('https://flutter-cn.firebaseio.com/products.json',body: json.encode(param),encoding: Utf8Codec()).then((http.Response response) {final Map responseData = json.decode(response.body);//处理响应数据}).catchError((error) {print('$error错误');});

返回值都用到Dart Futures,类似Javascript中的promise官方推荐使用async/await来调用网络请求

void addProduct(Product product) async {Map param = {'title': product.title,'description': product.description,'price': product.price};try {final http.Response response = await http.post('https://flutter-cn.firebaseio.com/products.json',body: json.encode(param),encoding: Utf8Codec());final Map responseData = json.decode(response.body);print('$responseData 数据');} catch (error) {print('$error错误');}}

用  try catch来捕获错误两种写法都可以,个人觉得第二种语法思路更明确。

 

附上一些常用库

name: stocksenvironment:# The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite.sdk: ">&#61;2.0.0-dev.68.0 <3.0.0"dependencies:flutter:sdk: flutterflutter_localizations:sdk: flutterintl: 0.15.7intl_translation: 0.17.2http: 0.12.0isolate: 2.0.2analyzer: 0.33.6&#43;1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"args: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"async: 2.0.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"charcode: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"collection: 1.14.11 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"convert: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"crypto: 2.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"csslib: 0.14.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"dart_style: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"front_end: 0.1.6&#43;9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"glob: 1.1.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"html: 0.13.3&#43;3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"http_parser: 3.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"kernel: 0.3.6&#43;9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"logging: 0.11.3&#43;2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"meta: 1.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"package_config: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"path: 1.6.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"petitparser: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"plugin: 0.2.0&#43;3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"pub_semver: 1.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"source_span: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"string_scanner: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"typed_data: 1.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"utf: 0.9.0&#43;5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"vector_math: 2.0.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"watcher: 0.9.7&#43;10 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"yaml: 2.1.15 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"dev_dependencies:flutter_test:sdk: flutterflutter_driver:sdk: flutterboolean_selector: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"file: 5.0.7 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"json_rpc_2: 2.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"matcher: 0.12.3&#43;1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"quiver: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"stack_trace: 1.9.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"stream_channel: 1.6.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"term_glyph: 1.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"test_api: 0.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"vm_service_client: 0.2.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"web_socket_channel: 1.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"flutter:uses-material-design: true# PUBSPEC CHECKSUM: 1b58

 

参考链接&#xff1a;dart中的http包讲解&#xff0c;flartter官方网站&#xff0c;Dart语言官方网站

 


推荐阅读
  • 本文介绍了在 Java 编程中遇到的一个常见错误:对象无法转换为 long 类型,并提供了详细的解决方案。 ... [详细]
  • 实验九:使用SharedPreferences存储简单数据
    本实验旨在帮助学生理解和掌握使用SharedPreferences存储和读取简单数据的方法,包括程序参数和用户选项。 ... [详细]
  • 本文介绍了如何在iOS平台上使用GLSL着色器将YV12格式的视频帧数据转换为RGB格式,并展示了转换后的图像效果。通过详细的技术实现步骤和代码示例,读者可以轻松掌握这一过程,适用于需要进行视频处理的应用开发。 ... [详细]
  • 本文探讨了资源访问的学习路径与方法,旨在帮助学习者更高效地获取和利用各类资源。通过分析不同资源的特点和应用场景,提出了多种实用的学习策略和技术手段,为学习者提供了系统的指导和建议。 ... [详细]
  • 深入解析 Android TextView 中 getImeActionLabel() 方法的使用与代码示例 ... [详细]
  • 探索聚类分析中的K-Means与DBSCAN算法及其应用
    聚类分析是一种用于解决样本或特征分类问题的统计分析方法,也是数据挖掘领域的重要算法之一。本文主要探讨了K-Means和DBSCAN两种聚类算法的原理及其应用场景。K-Means算法通过迭代优化簇中心来实现数据点的划分,适用于球形分布的数据集;而DBSCAN算法则基于密度进行聚类,能够有效识别任意形状的簇,并且对噪声数据具有较好的鲁棒性。通过对这两种算法的对比分析,本文旨在为实际应用中选择合适的聚类方法提供参考。 ... [详细]
  • 开发笔记:深入解析Android自定义控件——Button的72种变形技巧
    开发笔记:深入解析Android自定义控件——Button的72种变形技巧 ... [详细]
  • Android 图像色彩处理技术详解
    本文详细探讨了 Android 平台上的图像色彩处理技术,重点介绍了如何通过模仿美图秀秀的交互方式,利用 SeekBar 实现对图片颜色的精细调整。文章展示了具体的布局设计和代码实现,帮助开发者更好地理解和应用图像处理技术。 ... [详细]
  • 深入解析 Android 中 EditText 的 getLayoutParams 方法及其代码应用实例 ... [详细]
  • 在Python中,是否可以通过使用Tkinter或ttk库创建一个具有自动换行功能的多行标签,并使其宽度能够随着父容器的变化而动态调整?例如,在调整NotePad窗口宽度时,实现类似记事本的自动换行效果。这种功能在设计需要显示长文本的对话框时非常有用,确保文本内容能够完整且美观地展示。 ... [详细]
  • 掌握Android UI设计:利用ZoomControls实现图片缩放功能
    本文介绍了如何在Android应用中通过使用ZoomControls组件来实现图片的缩放功能。ZoomControls提供了一种简单且直观的方式,让用户可以通过点击放大和缩小按钮来调整图片的显示大小。文章详细讲解了ZoomControls的基本用法、布局设置以及与ImageView的结合使用方法,适合初学者快速掌握Android UI设计中的这一重要功能。 ... [详细]
  • 技术分享:深入解析GestureDetector手势识别机制
    技术分享:深入解析GestureDetector手势识别机制 ... [详细]
  • 本文探讨了在Android应用中实现动态滚动文本显示控件的优化方法。通过详细分析焦点管理机制,特别是通过设置返回值为`true`来确保焦点不会被其他控件抢占,从而提升滚动文本的流畅性和用户体验。具体实现中,对`MarqueeText.java`进行了代码层面的优化,增强了控件的稳定性和兼容性。 ... [详细]
  • Android目录遍历工具 | AppCrawler自动化测试进阶(第二部分):个性化配置详解
    终于迎来了“足不出户也能为社会贡献力量”的时刻,但有追求的测试工程师绝不会让自己的生活变得乏味。与其在家消磨时光,不如利用这段时间深入研究和提升自己的技术能力,特别是对AppCrawler自动化测试工具的个性化配置进行详细探索。这不仅能够提高测试效率,还能为项目带来更多的价值。 ... [详细]
  • PyQt5 QTextEdit:深入解析Python中多功能GUI库的应用与实现
    本文详细探讨了 PyQt5 中 QTextEdit 组件在 Python 多功能 GUI 库中的应用与实现。PyQt5 是 Qt 框架的 Python 绑定,提供了超过 620 个类和 6000 个函数及方法,广泛应用于跨平台应用程序开发。QTextEdit 作为其中的重要组件,支持丰富的文本编辑功能,如富文本格式、文本高亮和自定义样式等。PyQt5 的流行性不仅在于其强大的功能,还在于其易用性和灵活性,使其成为开发复杂用户界面的理想选择。 ... [详细]
author-avatar
美美琳子_899
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有