Flutter网络请求基础插件http_base_helper的使用
Flutter网络请求基础插件http_base_helper的使用
HttpBaseHelper 插件
简化并缩短使用 http
进行网络请求的过程。
示例
请求网络
// 获取共享偏好设置。
final httpBaseHelper = await ApiBaseHelper();
// 对于 GET 方法请求。
httpBaseHelper.onNetworkRequesting(method: Method.get, fullURL: "http://...").then((response) {
// 这里为状态码 200
debugPrint("response$response");
}).catchError((ErrorModel error, stackTrace) {
// 这里为错误状态码
debugPrint('状态码: ${error.statusCode}');
});
// 对于 POST 方法请求。
httpBaseHelper.onNetworkRequesting(method: Method.post, fullURL: "http://...", body: {
"id": 1
}).then((response) {
// 这里为状态码 200
debugPrint("response$response");
}).catchError((ErrorModel error, stackTrace) {
// 这里为错误状态码
debugPrint('状态码: ${error.statusCode}');
});
所有方法请求
// 对于 GET 请求
Method.get
// 对于 POST 请求
Method.post
// 对于 PUT 请求
Method.put
// 对于 DELETE 请求
Method.delete
完整示例代码
以下是一个完整的 Flutter 应用示例,演示如何使用 http_base_helper
插件进行网络请求。
import 'package:flutter/material.dart';
import 'package:http_base_helper/http_base_helper.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
[@override](/user/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](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final httpBaseHelper = ApiBaseHelper();
Future<void> onFetchAlbums() async {
debugPrint("is event calendar working1");
await httpBaseHelper
.onNetworkRequesting(
method: Method.get,
isAuthorize: false,
fullURL: 'https://jsonplaceholder.typicode.com/albums',
)
.then((response) => {debugPrint("Albums:$response")})
.catchError((ErrorModel error, stackTrace) =>
{debugPrint("is event calendar working2${error.bodyString}")});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
'You have pushed the button this many times:',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
onFetchAlbums();
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
更多关于Flutter网络请求基础插件http_base_helper的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复