新建一个util.dart
文件,在文件中写入如下转化方法(可根据具体显示需求调整内容)
///超过四位数的数字转化为w格式,如:38128 => 3.8w,381285 => 38.1w
formatCharCount(int count) {
if (count <= 0 || count.isNaN) {
return '0';
}
String strCount = count.toString();
if(strCount.length >= 5) {
String prefix = strCount.substring(0,strCount.length-4);
if(strCount.length == 5) {
prefix += '.${strCount[1]}';
}
if(strCount.length == 6) {
prefix += '.${strCount[2]}';
}
return prefix + 'w';
}
return strCount;
}
创建好转化方法后,在需要转化的数字外包裹一层formatCharCount
即可
示例:
import 'package:flutter/material.dart';
import 'package:demo/utils/util.dart';
class FormatCharCountPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text('Format Char Count Page')
),
body:Column(
children: <Widget> [
formatCharCount(1234), //转化后显示为1234
formatCharCount(12345), //转化后显示为1.2w
formatCharCount(123456), //转化后显示为12.3w
formatCharCount(1234567), //转化后显示为123w
],
),
);
}
}