Flutter DHIS2工具集插件dhis2_dart_utils的使用
Flutter DHIS2工具集插件dhis2_dart_utils的使用
标题
Flutter DHIS2工具集插件dhis2_dart_utils的使用
内容
-
DHIS2 DART UTILITIES
- A collection of data models, constants and utility functions used to build a DHIS2 app in dart.
-
Contents:
- Getting Started
- Testing and Development
- Usage
-
Features:
- Generator function for DHIS2 uid.
- Utilities, data models and constants for DHIS2 periods.
- DHIS2 Program indicator engine.
- DHIS2 Program rule engine.
- DHIS2 Program HTTP service.
-
Getting Started
- Package Installation
- For a dart project:
dart pub add dhis2_dart_utils
- for a flutter project:
flutter pub add dhis2_dart_utils
- Adding it directly on the
pubspec.yaml
dependencies and runningflutter pub get
ordart pub get
.
- For a dart project:
- Package Installation
-
Usage
-
How to Import:
import 'package:dhis2_dart_utils/dhis2_dart_utils.dart';
-
For more examples, click here: example/README.md
-
示例代码
import 'package:dhis2_dart_utils/dhis2_dart_utils.dart';
void main() {
// uid variable holds the generated uid
String uid = Core.getUid();
}
import 'package:dhis2_dart_utils/dhis2_dart_utils.dart';
void main() {
// Form data object
Map programIndicatorEngineDataObject = {
"vV9UWAZohSf": 12,
"qrur9Dvnyt5": 30,
"GieVkTxp4HH": 0.4,
};
// program indicators
List<ProgramIndicator> programIndicators = [
{
"id": "yFTplrY7NaL",
"aggregationType": "CUSTOM",
"expression": "(#{Zj7UnCAulEk.vV9UWAZohSs} * #{Zj7UnCAulEk.GieVkTxp4HH}) + (#{Zj7UnCAulEk.qrur9Dvnyt5})",
"program": "eBAyeGv0exc"
}
].map((indicator) => ProgramIndicator.fromMap(indicator)).toList();
// program indicator engine results
Map engineResults = ProgramIndicatorEngine.evaluateProgramIndicators(
programIndicators: programIndicators,
dataObject: programIndicatorEngineDataObject,
);
}
import 'package:dhis2_dart_utils/dhis2_dart_utils.dart';
void main() {
// Program rules
List<ProgramRule> programRules = [
{
"id": "fd3wL1quxGb",
"condition": "#{gender} == 'Male'",
"program": "eBAyeGv0exc",
"programRuleActions": [
{
"id": "IrmpncBsypT",
"programRuleActionType": "HIDEFIELD",
"programRule": "fd3wL1quxGb",
"dataElement": "SWfdB5lX0fk",
"programStageSection": "d7ZILSbPgYh"
}
]
},
{
"id": "xZe5qCzRS0Y",
"condition": "#{gender} == 'Male'",
"program": "lxAQ7Zs9VYR",
"programRuleActions": [
{
"id": "hwgyO59SSxu",
"programRuleActionType": "ASSIGN",
"programRule": "xOe5qCzRS0Y",
"dataElement": "sWoqcoByYmD",
"data": "false"
}
]
},
{
"id": "xOe5qCzRS0Y",
"condition": "!#{womanSmoking}",
"program": "lBAyeGv0exc",
"programRuleActions": [
{
"id": "hwgyO59SSxu",
"programRuleActionType": "HIDEFIELD",
"programRule": "xOe5qCzRS0Y",
"dataElement": "sWoqcoByYmD",
"data": "false"
}
]
}
]
.map((Map<String, dynamic> programRule) => ProgramRule.fromMap(programRule))
.toList();
// Program rule variables
List<ProgramRuleVariable> programRuleVariables = [
{
"name": "gender",
"id": "zINGRka3g9N",
"programRuleVariableSourceType": "DATAELEMENT_NEWEST_EVENT_PROGRAM",
"program": "eBAyeGv0exc",
"dataElement": "oZg33kd9taw"
},
{
"name": "womanSmoking",
"id": "Z92dJO9gIje",
"programRuleVariableSourceType": "DATAELEMENT_NEWEST_EVENT_PROGRAM",
"program": "lBAyeGv0exc",
"dataElement": "sWoqcoByYmD"
}
]
.map((Map<String, dynamic> programRuleVariable) => ProgramRuleVariable.fromMap(programRuleVariable))
.toList();
// Form data object
Map programRuleEngineDataObject = {
"oZg33kd9taw": "Male",
};
Map engineResult = ProgramRuleEngine.evaluateProgramRule(
programRules: programRules,
programRuleVariables: programRuleVariables,
dataObject: programRuleEngineDataObject,
);
}
import 'dart:convert';
import 'dart:math';
import 'package:dhis2_dart_utils/dhis2_dart_utils.dart';
void main() {
// Credentials
Map<String, dynamic> credentials = {
"username": "system",
"password": "District1#",
"serverUrl": "https://dev.hisspztz.com/dhis2/"
};
// Query Parameters
Map<String, dynamic> queryParameters = {};
// Api Endpoint
String url = "api/dataStore/httpTests/${Random().nextInt(77)}";
// Api Token
String apiToken = "d2pat_oz1mQxGlckO14bjHvi3r7Or5EOAxCn2K2104519092";
// Body
Map<String, dynamic> body = {
"id": Random().nextInt(77),
"name": "Testing Http Service functions",
};
String domainHost = HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken)
).domainHost;
String domainPath = HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).domainPath;
final uri = HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).getApiUrl(url, queryParameters: queryParameters);
// POST Request
final response = await HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).httpPost(url, jsonEncode(body));
// GET Request
final response = await HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).httpGet(url);
// DELETE Request
final response = await HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).httpDelete(url);
// PUT Request
final response = await HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).httpPut(url, jsonEncode(body));
// GET Pagination Request
final response = await HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).httpGetPagination(url, queryParameters);
String serverUrl = HttpService(
serverUrl: credentials["serverUrl"],
apiToken: apiToken
).toString();
}
更多关于Flutter DHIS2工具集插件dhis2_dart_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter DHIS2工具集插件dhis2_dart_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用dhis2_dart_utils
插件的一些代码示例。这个插件通常用于与DHIS2服务器进行交互,处理常见的DHIS2 API请求和数据解析。
首先,确保你已经在pubspec.yaml
文件中添加了dhis2_dart_utils
依赖:
dependencies:
flutter:
sdk: flutter
dhis2_dart_utils: ^最新版本号 # 请替换为实际的最新版本号
然后运行flutter pub get
来获取依赖。
初始化客户端
在使用任何功能之前,你需要初始化一个DHIS2客户端。这通常涉及到设置API的基础URL和认证信息。
import 'package:dhis2_dart_utils/dhis2_dart_utils.dart';
void main() async {
// 创建DHIS2客户端实例
final client = Dhis2Client(
baseUrl: 'https://your-dhis2-server.org/api',
username: 'your-username',
password: 'your-password',
);
// 登录(如果需要的话,某些实现可能已经封装了自动登录逻辑)
await client.authenticate();
// 现在你可以使用client进行API调用
runApp(MyApp(client: client));
}
获取元数据
元数据是DHIS2系统中的重要部分,它包含了数据模型的信息,比如数据元素、程序规则等。
import 'package:dhis2_dart_utils/core/models/metadata.dart';
Future<void> fetchMetadata(Dhis2Client client) async {
try {
final metadata = await client.fetchMetadata();
print('Fetched Metadata: ${metadata.toJson()}');
} catch (e) {
print('Error fetching metadata: $e');
}
}
获取数据值
从DHIS2获取数据值通常涉及到指定数据元素、时间段和组织单元。
import 'package:dhis2_dart_utils/core/models/data_value.dart';
import 'package:dhis2_dart_utils/core/models/period.dart';
Future<void> fetchDataValues(Dhis2Client client) async {
try {
final dataElementId = 'dataElementId'; // 替换为实际的数据元素ID
final pe = Period.fromIsoString('2023-01'); // 指定时间段
final orgUnitId = 'orgUnitId'; // 替换为实际的组织单元ID
final dataValues = await client.getDataValues(
dataElementIds: [dataElementId],
pe: pe,
orgUnitId: orgUnitId,
);
print('Fetched Data Values: ${dataValues.map((e) => e.toJson()).toList()}');
} catch (e) {
print('Error fetching data values: $e');
}
}
提交数据值
提交数据值到DHIS2服务器,你需要指定数据元素、组织单元、周期以及实际的值。
import 'package:dhis2_dart_utils/core/models/data_value_set.dart';
import 'package:dhis2_dart_utils/core/models/data_value.dart';
Future<void> postDataValues(Dhis2Client client) async {
try {
final dataValueSet = DataValueSet(
dataValues: [
DataValue(
dataElement: 'dataElementId', // 替换为实际的数据元素ID
period: '202301', // 周期,可以是ISO字符串或其他格式,取决于服务器配置
orgUnit: 'orgUnitId', // 替换为实际的组织单元ID
value: '123', // 实际的值
storedBy: 'yourUsername', // 存储者的用户名
),
],
);
await client.postDataValueSet(dataValueSet);
print('Data values posted successfully');
} catch (e) {
print('Error posting data values: $e');
}
}
错误处理
在实际应用中,你应该添加更多的错误处理逻辑,以确保应用程序的健壮性。这可以通过try-catch块、错误日志记录以及用户友好的错误消息来实现。
结论
dhis2_dart_utils
插件为Flutter开发者提供了一个强大的工具集,用于与DHIS2服务器进行交互。上述代码示例展示了如何初始化客户端、获取元数据、获取数据值以及提交数据值。根据你的具体需求,你可以进一步扩展这些示例。