'String' 型不是 CAST FLUTTER 类型中 'double' 型的子类型



我正在尝试调用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: List<dynamic>.from(json["result"])
.map((i) => ResultClass.fromJson(i))
.toList()
);
Map<String, dynamic> toJson() => {
"success": success,
"result": result.map((item) => item.toJson()).toList(),
};
}
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: json["rate"] as double,
lastprice: json["lastprice"] as double,
lastpricestr: json["lastpricestr"],
hacim: json["hacim"] as double,
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,
};
}

这就是我所说的API:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../models/apis/hisselist.dart';
class Stocks extends StatefulWidget {
Stocks({Key? key}) : super(key: key);
@override
_StocksState createState() => _StocksState();
}
class _StocksState extends State<Stocks> with AutomaticKeepAliveClientMixin {

ScrollController? controller;
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 xxx'
};
final response = await http.get(url,headers:requestHeaders);
if(response.statusCode == 200){
var result = hisselistFromJson(response.body);
if(mounted);
setState(() {
counter = result.result.length;
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) {
super.build(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.builder(
itemCount: counter,
itemBuilder: (context, index){
return Card(
child: ListTile(
title: Text(hisseResult?.result[index].code??""),
subtitle: Text(hisseResult?.result[index].code??""),                  ),
);
}) : Center(child: CircularProgressIndicator(
)),
),
),
);

}
@override
bool get wantKeepAlive => true;
}

我在控制台上得到了这个,API没有显示:

类型"String"不是类型强制转换中类型"double"的子类型

如何修复此问题?

最好使用.tryParse,而不是强制使用as前缀。尝试使用非字符串值

lastprice: double.tryParse(json["lastprice"]) ?? 0.0,
factory ResultClass.fromJson(Map<String, dynamic> json) => ResultClass(
rate: double.tryParse(json["rate"]) ?? 0.0,
lastprice: double.tryParse(json["lastprice"]) ?? 0.0,
lastpricestr: json["lastpricestr"],
hacim: double.tryParse(json["hacim"]) ?? 0.0,
hacimstr: json["hacimstr"],
text: json["text"],
code: json["code"],
);

试试这个,当你喜欢使用任何double作为字符串时,请使用.toString()

class ResultClass {
final double rate;
final double lastprice;
final String lastpricestr;
final double hacim;
final String hacimstr;
final String text;
final String code;
ResultClass({
required this.rate,
required this.lastprice,
required this.lastpricestr,
required this.hacim,
required this.hacimstr,
required this.text,
required this.code,
});
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'rate': rate});
result.addAll({'lastprice': lastprice});
result.addAll({'lastpricestr': lastpricestr});
result.addAll({'hacim': hacim});
result.addAll({'hacimstr': hacimstr});
result.addAll({'text': text});
result.addAll({'code': code});
return result;
}
factory ResultClass.fromMap(Map<String, dynamic> map) {
return ResultClass(
rate: map['rate']?.toDouble() ?? 0.0,
lastprice: map['lastprice']?.toDouble() ?? 0.0,
lastpricestr: map['lastpricestr'] ?? '',
hacim: map['hacim']?.toDouble() ?? 0.0,
hacimstr: map['hacimstr'] ?? '',
text: map['text'] ?? '',
code: map['code'] ?? '',
);
}
String toJson() => json.encode(toMap());
factory ResultClass.fromJson(String source) =>
ResultClass.fromMap(json.decode(source));
}

而不是rate:map['rate']?。toDouble((??0.0,

尝试率:双倍。parse(map['rate']??'0'(,

可能是由于您从API获取字符串而导致的运行时错误,在该API中您声明了一个double。

如果您当时还不确定是哪种变量类型,则声明var变量。

因此,首先你要检查哪个变量类型来自API

对于Exapi响应:{"速率":"1.0〃;}

你在班上这样申报双倍速率=0.0;

最新更新