flutterrestdartnull-safety

type 'String' is not a subtype of type 'double' in type cast flutter


I'm trying to call an API. This is my model file:

// 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,
  };
}

This is where I call the 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;
}

I'm getting this on the console and API is not showing:

type 'String' is not a subtype of type 'double' in type cast

How can I fix this?


Solution

  • It is better to use .tryParse instead of forcing with as prefix. Try this for non string value

     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"],
      );
    

    Try this and when ever you like to use any double as string use .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));
    }