Flutter中如何将数字状态转换为文本显示
问题描述
数据库中以数字0和1存储状态,希望在Flutter的ListView Builder组件中展示时,将数字转换为对应文本:0对应“待审批”,1对应“已通过”,刚接触Flutter,求实现方法。
我当前的代码
class _view_problemState extends State<view_problem> { TextEditingController _searchController = TextEditingController(); List<problemModel> problemlist = []; List<problemModel> originalList = []; StreamController _streamController = StreamController(); Future getAllProblem() async { problemlist = await problemcontrollers().getProblem(); originalList = problemlist; _streamController.sink.add(problemlist); } @override void initState() { getAllProblem(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color.fromARGB(255, 14, 12, 134), title: const Text('show information'), ), body: Container( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), ), Expanded( child: StreamBuilder( stream: _streamController.stream, builder: (context, snapshots) { if (snapshots.hasData) { return ListView.builder( itemCount: problemlist.length, itemBuilder: ((context, index) { problemModel problem = problemlist[index]; return Card( margin: EdgeInsets.all(10), child: ListTile( leading: CircleAvatar( backgroundImage: NetworkImage( 'http://192.168.1.5/skc/Problem_image/${problem.image}', ), ), title: Text( problem.name_surname, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 19), ), subtitle: Text( problem.status, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ), ), ); })); } return Center( child: CircularProgressIndicator(), ); }, ), ) ], ), ), ); } }
解决方案
提供三种简单的实现方式,根据你的习惯选择:
方式一:直接在UI层判断转换(最快捷)
直接在subtitle的Text组件里通过三元运算符判断状态值,转换为对应文本。注意要根据problem.status的实际类型调整判断条件(如果是字符串类型用problem.status == '0',数字类型用problem.status == 0):
subtitle: Text( problem.status == 0 ? '待审批' : '已通过', // 按实际类型调整判断逻辑 style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ),
方式二:在Model层添加getter方法(更优雅)
在problemModel类中添加一个计算属性,专门返回转换后的状态文本,UI层直接调用即可,避免重复写判断逻辑:
class problemModel { // 假设你的Model已有以下字段 int status; // 或String status,根据实际情况调整 String name_surname; String image; // 其他构造函数、序列化逻辑... // 添加状态文本转换的getter String get statusText { if (status == 0) { // 字符串类型则写 status == '0' return '待审批'; } else if (status == 1) { return '已通过'; } return '未知状态'; // 处理异常值 } }
UI层直接使用这个属性:
subtitle: Text( problem.statusText, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ),
方式三:抽成工具函数(复用性高)
如果多个页面都需要状态转换,可以写一个全局工具函数:
String getStatusText(dynamic status) { if (status == 0 || status == '0') { return '待审批'; } else if (status == 1 || status == '1') { return '已通过'; } return '未知状态'; }
UI层调用该函数:
subtitle: Text( getStatusText(problem.status), style: TextStyle( fontWeight: FontWeight.bold, fontSize: 17), ),
内容的提问来源于stack exchange,提问作者john Gamey
相关产品推荐
相关产品推荐

