Flutter中移除API返回code字段的https:前缀实现方案问询
如何移除Flutter模型中API返回的code字段的"https:"前缀
调用https://api.collectapi.com/economy/hisseSenedi接口后,返回的result列表中每个item的code字段带有"https:"前缀,导致界面展示不符合需求。以下是项目中使用的模型代码与API调用代码,需要实现移除该前缀的方法:
模型代码
/* // To parse this JSON data, do // // final hisselist = hisselistFromJson(jsonString); import 'dart:convert'; Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str)); String hisselistToJson(Hisselist data) => json.encode(data.toJson()); class Hisselist { Hisselist({ required this.success, required this.result, }); bool success; List<ResultClass> result; factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist( success: json["success"], result: json["result"].map<ResultClass>((x) => ResultClass.fromJson(x)).toList(), ); Map<String, dynamic> toJson() => { "success": success, "result": result.map((x) => x.toJson()), }; } class ResultClass { ResultClass({ required this.rate, required this.lastprice, required this.lastpricestr, required this.hacim, required this.hacimstr, required this.text, required this.code, }); double rate; double lastprice; String lastpricestr; double hacim; String hacimstr; String text; String code; factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass( rate: double.tryParse(json["rate"].toString()) ?? 0.0, lastprice: double.tryParse(json["lastprice"].toString()) ?? 0.0, lastpricestr: json["lastpricestr"], hacim: double.tryParse(json["hacim"].toString()) ?? 0.0, hacimstr: json["hacimstr"], text: json["text"], code: json["code"], ); Map<String, dynamic> toJson() => { "rate": rate, "lastprice": lastprice, "lastpricestr": lastpricestr, "hacim": hacim, "hacimstr": hacimstr, "text": text, "code": code, }; } */ // To parse this JSON data, do // // final hisselist = hisselistFromJson(jsonString); import 'dart:convert'; Hisselist hisselistFromJson(String str) => Hisselist.fromJson(json.decode(str)); String hisselistToJson(Hisselist data) => json.encode(data.toJson()); class Hisselist { Hisselist({ required this.success, required this.result, }); bool success; List<Result> result; factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist( success: json["success"], result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))), ); Map<String, dynamic> toJson() => { "success": success, "result": List<dynamic>.from(result.map((x) => x.toJson())), }; } class Result { Result({ this.rate, this.lastprice, this.lastpricestr, this.hacim, this.hacimstr, this.min, this.minstr, this.max, this.maxstr, this.time, this.text, this.code, }); double? rate; double? lastprice; String? lastpricestr; String? hacim; String? hacimstr; dynamic min; String? minstr; dynamic max; String? maxstr; Time? time; String? text; String? code; factory Result.fromJson(Map<String, dynamic> json) => Result( rate: json["rate"].toDouble(), lastprice: json["lastprice"].toDouble(), lastpricestr: json["lastpricestr"], hacim: json["hacim"], hacimstr: json["hacimstr"], min: json["min"], minstr: json["minstr"], max: json["max"], maxstr: json["maxstr"], time: timeValues.map[json["time"]], text: json["text"], code: json["code"], ); Map<String, dynamic> toJson() => { "rate": rate, "lastprice": lastprice, "lastpricestr": lastpricestr, "hacim": hacim, "hacimstr": hacimstr, "min": min, "minstr": minstr, "max": max, "maxstr": maxstr, "time": timeValues.reverse[time], "text": text, "code": code, }; } enum Time { THE_1809, THE_1808, THE_1805, THE_1810, THE_1759, THE_1755 } final timeValues = EnumValues({ "17:55": Time.THE_1755, "17:59": Time.THE_1759, "18:05": Time.THE_1805, "18:08": Time.THE_1808, "18:09": Time.THE_1809, "18:10": Time.THE_1810 }); class EnumValues<T> { Map<String, T> map; Map<T, String>? reverseMap; EnumValues(this.map); Map<T, String> get reverse { if (reverseMap == null) { reverseMap = map.map((k, v) => new MapEntry(v, k)); } return reverseMap!; } }
API调用代码
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import '../models/apis/hisselist.dart'; class Hisseler extends StatefulWidget { const Hisseler({Key? key}) : super(key: key); @override State<Hisseler> createState() => _HisselerState(); } class _HisselerState extends State<Hisseler> { final scaffoldKey = GlobalKey<ScaffoldState>(); final url = Uri.parse('https://api.collectapi.com/economy/hisseSenedi'); var counter; Hisselist? hisseResult; Future callHisse() async { try{ Map<String, String> requestHeaders = { 'Content-Type': 'application/json', 'Authorization': 'apikey 4xxxxP' }; final response = await http.get(url,headers:requestHeaders); if(response.statusCode == 200){ var result = hisselistFromJson(response.body); if(mounted); setState(() { counter = result.result.length; result.result.sort((a, b) => (a.text ?? "").compareTo(b.text ?? "")); hisseResult = result; }); return result; } else { print(response.statusCode); } } catch(e) { print(e.toString()); } } @override void initState() { // TODO: implement initState super.initState(); callHisse(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: false, automaticallyImplyLeading: false, title: Text( 'Hisseler' ), ), body: Center( child: Padding( padding: const EdgeInsets.all(8.0), child: counter != null ? ListView.separated( itemCount: counter, separatorBuilder: (context, index) { return Divider(color: Colors.grey[400]); }, itemBuilder: (context, index){ return Card( child: ListTile( contentPadding: EdgeInsets.all(10), title: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(hisseResult?.result[index].code??"", style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500)), Text(hisseResult?.result[index].text??"",style: TextStyle(color: Colors.grey[500], fontSize: 14)) ], ), trailing: Column( children: <Widget>[ Text(hisseResult?.result[index].lastpricestr??"", style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500)), Container( alignment: Alignment.center, decoration: BoxDecoration( borderRadius: BorderRadius.circular(5), color: Colors.red ), width: 75, height: 25, child: Text(hisseResult?.result[index].rate.toString()??"",style: TextStyle(color: Colors.white)) ) ], ), ),); }) : Center(child: CircularProgressIndicator( )), ), ), ); } }
解决方案
方法1:在模型解析时处理(推荐)
直接在Result类的fromJson工厂方法中处理code字段,这样所有使用该模型的地方拿到的code都是已经移除前缀的,无需重复编写处理逻辑:
修改Result.fromJson中的code赋值部分:
factory Result.fromJson(Map<String, dynamic> json) => Result( // 其他字段保持不变 text: json["text"], code: json["code"]?.toString().startsWith("https:") == true ? json["code"].toString().substring("https:".length) : json["code"], );
如果接口返回的前缀是固定的"https:",也可以用replaceFirst简化:
code: json["code"]?.toString().replaceFirst("https:", "") ?? json["code"],
方法2:在UI展示时临时处理
如果不想修改模型,仅在当前界面展示时移除前缀,直接修改Text组件的内容即可:
Text( hisseResult?.result[index].code?.replaceFirst("https:", "") ?? "", style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500) ),
或者用substring方式(确保code不为null且确实以"https:"开头):
Text( hisseResult?.result[index].code != null && hisseResult!.result[index].code!.startsWith("https:") ? hisseResult!.result[index].code!.substring("https:".length) : hisseResult?.result[index].code ?? "", style: TextStyle(color: Colors.black, fontSize: 16, fontWeight: FontWeight.w500) ),
内容的提问来源于stack exchange,提问作者Mıktad Tahir Durak
相关产品推荐
相关产品推荐

