dart 类型“String”不是类型强制转换flutter中类型“double”的子类型

m4pnthwp  于 2023-07-31  发布在  Flutter
关注(0)|答案(3)|浏览(147)

我正在调用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”的子类型
我该怎么解决这个问题?

c8ib6hqw

c8ib6hqw1#

最好使用.tryParse,而不是强制使用as前缀。尝试对非字符串值执行此操作

lastprice: double.tryParse(json["lastprice"]) ?? 0.0,

个字符
尝试一下,当你喜欢使用任何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));
}

4dc9hkyq

4dc9hkyq2#

而不是评级:map['rate']?.toDouble()??0.0,
try rate:double.parse(map['rate']??'0'),

fsi0uk1n

fsi0uk1n3#

可能是运行时错误,因为您从声明了double的API中获取字符串。
如果您不确定此时的变量类型,则声明var变量。
首先你检查哪个变量类型来自API
对于Ex API响应:{“rate”:“1.0”}
你在类中声明双倍利率= 0.0

相关问题