Flutter网络请求插件gits_http的使用
Flutter网络请求插件gits_http的使用
gits_http
是一个基于 http
库封装的Flutter网络请求插件,支持多种HTTP请求方法,并且提供了方便的Token管理、刷新Token以及网络请求调试等功能。本文将详细介绍如何使用该插件。
初始化GitsHttp
首先,我们需要在项目中注册 GitsHttp
实例到 locator
中,以便在应用中全局使用。
添加依赖
在 pubspec.yaml
文件中添加以下依赖:
dependencies:
http: ^0.13.5
gits_inspector: ^1.0.0
get_it: ^7.2.0
flutter_secure_storage: ^6.0.0
gits_http: ^1.0.0
注册服务
在项目的初始化部分(如 main.dart
)中,注册 GitsHttp
和 GitsInspector
到 GetIt
的 locator
中:
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:gits_http/gits_http.dart';
import 'package:gits_inspector/gits_inspector.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
final locator = GetIt.instance;
void setupLocator() {
// 注册 GitsHttp 实例
locator.registerLazySingleton(
() => GitsHttp(
timeout: 30000,
showLog: true,
gitsInspector: locator(),
authTokenOption: AuthTokenOption(
typeHeader: 'Authorization',
prefixHeader: 'Bearer',
getToken: () => locator<FlutterSecureStorage>().read(key: 'token'),
authCondition: (request, response) =>
request.url == GitsEndpoints.login,
onAuthTokenResponse: (response) async {
final map = jsonDecode(response.body);
await locator<FlutterSecureStorage>().write(
key: 'token',
value: map['token'],
);
await locator<FlutterSecureStorage>().write(
key: 'refresh_token',
value: map['refresh_token'],
);
},
clearCondition: (request, response) =>
request.url == GitsEndpoints.logout,
onClearToken: () =>
locator<FlutterSecureStorage>().delete(key: 'token'),
excludeEndpointUsageToken: [
GitsEndpoints.login,
GitsEndpoints.register,
],
),
refreshTokenOption: RefreshTokenOption(
method: RefreshTokenMethod.post,
url: GitsEndpoints.refreshToken,
condition: (request, response) =>
request.url != GitsEndpoints.login && response.statusCode == 401,
getBody: () async {
final refreshToken =
await locator<FlutterSecureStorage>().read(key: 'refresh_token');
return {
'refresh_token': refreshToken ?? '',
};
},
onResponse: (response) async {
// handle response refresh token
final map = jsonDecode(response.body);
locator<FlutterSecureStorage>().write(
key: 'token',
value: map['token'],
);
},
),
),
);
// 注册 GitsInspector 实例
locator.registerLazySingleton(
() => GitsInspector(
showNotification: true, // default true
showInspectorOnShake: true, // default true
saveInspectorToLocal: true, // default true
notificationIcon: '@mipmap/ic_launcher', // default '@mipmap/ic_launcher' just for android
),
);
// 注册 FlutterSecureStorage 实例
locator.registerLazySingleton(() => const FlutterSecureStorage());
}
使用示例
GET 请求
final GitsHttp http = locator();
final response = await http.get(Uri.parse('https://api.gits.id'));
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed with status: ${response.statusCode}');
}
POST 请求
final GitsHttp http = locator();
try {
final response = await http.post(
Uri.parse('https://reqres.in/api/login'),
body: {"email": "eve.holt@reqres.in", "password": "cityslicka"},
);
print(response.body);
} on GitsException catch (e) {
final failure = e.toGitsFailure();
print(failure.toString());
} catch (e) {
print(e.toString());
}
PUT 请求
final GitsHttp http = locator();
final response = await http.put(
Uri.parse('https://api.gits.id/resource/1'),
body: {"key": "value"},
);
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed with status: ${response.statusCode}');
}
PATCH 请求
final GitsHttp http = locator();
final response = await http.patch(
Uri.parse('https://api.gits.id/resource/1'),
body: {"key": "new_value"},
);
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed with status: ${response.statusCode}');
}
DELETE 请求
final GitsHttp http = locator();
final response = await http.delete(
Uri.parse('https://api.gits.id/resource/1'),
);
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed with status: ${response.statusCode}');
}
Multipart POST 请求
final GitsHttp http = locator();
final File file = getImage(); // 获取文件的方法
final response = await http.postMultipart(
Uri.parse('https://api.gits.id/upload'),
files: {'image': file},
body: {"key": "value"},
);
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed with status: ${response.statusCode}');
}
完整示例Demo
以下是一个完整的示例代码,展示了如何在Flutter项目中使用 gits_http
插件进行网络请求:
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:gits_http/gits_http.dart';
import 'package:gits_inspector/gits_inspector.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// 注册服务
final locator = GetIt.instance;
void setupLocator() {
locator.registerLazySingleton(
() => GitsHttp(
timeout: 30000,
showLog: true,
gitsInspector: locator(),
authTokenOption: AuthTokenOption(
typeHeader: 'Authorization',
prefixHeader: 'Bearer',
getToken: () => locator<FlutterSecureStorage>().read(key: 'token'),
authCondition: (request, response) =>
request.url == GitsEndpoints.login,
onAuthTokenResponse: (response) async {
final map = jsonDecode(response.body);
await locator<FlutterSecureStorage>().write(
key: 'token',
value: map['token'],
);
await locator<FlutterSecureStorage>().write(
key: 'refresh_token',
value: map['refresh_token'],
);
},
clearCondition: (request, response) =>
request.url == GitsEndpoints.logout,
onClearToken: () =>
locator<FlutterSecureStorage>().delete(key: 'token'),
excludeEndpointUsageToken: [
GitsEndpoints.login,
GitsEndpoints.register,
],
),
refreshTokenOption: RefreshTokenOption(
method: RefreshTokenMethod.post,
url: GitsEndpoints.refreshToken,
condition: (request, response) =>
request.url != GitsEndpoints.login && response.statusCode == 401,
getBody: () async {
final refreshToken =
await locator<FlutterSecureStorage>().read(key: 'refresh_token');
return {
'refresh_token': refreshToken ?? '',
};
},
onResponse: (response) async {
final map = jsonDecode(response.body);
locator<FlutterSecureStorage>().write(
key: 'token',
value: map['token'],
);
},
),
),
);
locator.registerLazySingleton(
() => GitsInspector(
showNotification: true,
showInspectorOnShake: true,
saveInspectorToLocal: true,
notificationIcon: '@mipmap/ic_launcher',
),
);
locator.registerLazySingleton(() => const FlutterSecureStorage());
}
void main() {
setupLocator();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() async {
final GitsHttp http = locator();
try {
final response = await http.post(
Uri.parse('https://reqres.in/api/login'),
body: {"email": "eve.holt@reqres.in", "password": "cityslicka"},
);
print(response.body);
setState(() {
_counter++;
});
} on GitsException catch (e) {
final failure = e.toGitsFailure();
print(failure.toString());
} catch (e) {
print(e.toString());
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
更多关于Flutter网络请求插件gits_http的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络请求插件gits_http的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个使用 gits_http
插件进行网络请求的 Flutter 代码示例。请注意,gits_http
并非一个广泛认知的标准 Flutter 插件,因此我假设它的使用方式类似于其他 HTTP 客户端插件(如 dio
或 http
)。如果 gits_http
有特定的 API 或用法,请参考其官方文档进行调整。
首先,确保在 pubspec.yaml
文件中添加了 gits_http
依赖项(假设它存在于 pub.dev 或其他 Flutter 包仓库中):
dependencies:
flutter:
sdk: flutter
gits_http: ^x.y.z # 替换为实际版本号
然后,运行 flutter pub get
来获取依赖项。
接下来是一个简单的 Flutter 应用示例,演示如何使用 gits_http
进行 GET 和 POST 请求:
import 'package:flutter/material.dart';
import 'package:gits_http/gits_http.dart'; // 假设导入路径正确
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter GitsHttp Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String responseText = "";
void _makeGetRequest() async {
try {
var response = await GitsHttp.get('https://api.example.com/data');
if (response.isOk) {
setState(() {
responseText = response.data.toString();
});
} else {
setState(() {
responseText = "Error: ${response.statusCode}";
});
}
} catch (e) {
setState(() {
responseText = "Error: $e";
});
}
}
void _makePostRequest() async {
try {
var body = {
'key1': 'value1',
'key2': 'value2',
};
var response = await GitsHttp.post('https://api.example.com/submit', body: body);
if (response.isOk) {
setState(() {
responseText = response.data.toString();
});
} else {
setState(() {
responseText = "Error: ${response.statusCode}";
});
}
} catch (e) {
setState(() {
responseText = "Error: $e";
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GitsHttp Demo'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Text('Response:', style: TextStyle(fontSize: 18)),
Text(responseText, style: TextStyle(fontSize: 16)),
SizedBox(height: 20),
ElevatedButton(
onPressed: _makeGetRequest,
child: Text('Make GET Request'),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: _makePostRequest,
child: Text('Make POST Request'),
),
],
),
),
);
}
}
在这个示例中:
GitsHttp.get
用于执行 GET 请求。GitsHttp.post
用于执行 POST 请求,并传递请求体body
。- 响应数据存储在
responseText
变量中,并在 UI 中显示。
请注意,这里的 GitsHttp
类的使用是假设性的,具体 API 可能有所不同。如果 gits_http
插件的 API 不同,请参考其官方文档进行相应调整。
此外,确保你处理网络请求时的错误处理和安全性,例如使用 HTTPS、验证响应数据、处理超时等。