54 lines
1.5 KiB
Dart
54 lines
1.5 KiB
Dart
import 'package:blog_app/models/common.dart';
|
|
|
|
List<T> convertListResponse<T>(
|
|
dynamic data,
|
|
T Function(Map<String, dynamic>) fromJson,
|
|
) {
|
|
if (data is List) {
|
|
return data.map((item) => fromJson(item as Map<String, dynamic>)).toList();
|
|
}
|
|
throw FormatException(
|
|
'Expected a list of items for conversion, but got ${data.runtimeType}',
|
|
);
|
|
}
|
|
|
|
PageResult<T> convertPageResponse<T>(
|
|
dynamic data,
|
|
T Function(Map<String, dynamic>) fromJson,
|
|
) {
|
|
if (data is Map<String, dynamic>) {
|
|
return PageResult<T>.fromJson(
|
|
data,
|
|
(json) => fromJson(json as Map<String, dynamic>),
|
|
);
|
|
}
|
|
throw FormatException(
|
|
'Expected a Map for page response conversion, but got ${data.runtimeType}',
|
|
);
|
|
}
|
|
|
|
/// 将数字格式化为中文单位(万/亿)
|
|
String formatChineseDecimal(num number, {int decimalPlaces = 2}) {
|
|
if (number < 10000) {
|
|
return number.toString();
|
|
} else if (number < 100000000) {
|
|
// 万单位
|
|
double result = number / 10000.0;
|
|
return '${_formatDecimal(result, decimalPlaces)}万';
|
|
} else {
|
|
// 亿单位
|
|
double result = number / 100000000.0;
|
|
return '${_formatDecimal(result, decimalPlaces)}亿';
|
|
}
|
|
}
|
|
|
|
String _formatDecimal(double number, int decimalPlaces) {
|
|
// 去除末尾的0和小数点
|
|
String formatted = number.toStringAsFixed(decimalPlaces);
|
|
if (formatted.contains('.')) {
|
|
formatted = formatted.replaceAll(RegExp(r'0*$'), '');
|
|
formatted = formatted.replaceAll(RegExp(r'\.$'), '');
|
|
}
|
|
return formatted;
|
|
}
|