flutter:安装使用第三方库:以dio为例(flutter 3.7.0 / dio 4.0.6)
一,dio库的地址:
国外:
https://pub.dev/packages/dio
国内:
https://pub.flutter-io.cn/packages/dio
如图:可以看到最新版本是4.0.6
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/04/flutter-an-zhuang-shi-yong-di-san-fang-ku-yi-dio-wei-li/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,在项目中添加dio
1,修改: pubspec.yaml
添加dio,如图:
2,下载:
点击 Pub get 按钮
如图:
更新后pubspec.lock中会记录有dio的详累信息,如图:
三,在项目中实际应用dio
import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; import 'dart:convert'; import 'dart:io'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { //int _counter = 0; String _title = "标题"; String _author = "作者"; String _content = "静夜思"; void setContent(String content,title,author) { setState(() { _content = content; _title = title; _author = author; }); } void getHttp() async { String url = 'http://www.lhdtest.com/item/one?id=1'; try { var response = await Dio().get(url); print(response); if (response.statusCode == HttpStatus.ok) { var data= jsonDecode(response.toString()); print(data); setContent(data['data']['content'],data['data']['title'],data['data']['author']); } } catch (e) { print(e); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: (){ print("按钮被点击了:"); getHttp(); }, child: Text( '获取远程数据', style: TextStyle( color: Colors.white, ), ), ), Text( '$_title', ), Text( '$_author', ), Text( '$_content', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), ); } }
四,运行测试效果
五,查看flutter的版本:
liuhongdi@liuhongdideMBP ~ % flutter --version Flutter 3.7.0 • channel stable • https://github.com/flutter/flutter.git Framework • revision b06b8b2710 (7 days ago) • 2023-01-23 16:55:55 -0800 Engine • revision b24591ed32 Tools • Dart 2.19.0 • DevTools 2.20.1