【问题标题】:Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>' when converting JSON to a Map<String, dynamic> in Flutter未处理的异常:在 Flutter 中将 JSON 转换为 Map<String, dynamic> 时,“String”类型不是“Map<String, dynamic>”类型的子类型
【发布时间】:2022-06-26 10:19:50
【问题描述】:

Flask JSON 页面,如图: 或者,这里是 JSON 文件:

["{\"atl_change_percentage\": 4914281715.26934, \"image\": \"https://assets.coingecko.com/coins/images/4934/large/0_Black-svg.png?1600757954\", \"market_cap_rank\": 987, \"max_supply\": null, \"id\": \"0chain\", \"atl\": 2.65e-09, \"price_change_24h\": -5.1138319612315e-05, \"current_price\": 0.128283, \"last_updated\": \"2022-06-23T16:10:11.148Z\", \"ath\": 5.16, \"low_24h\": 0.124866, \"market_cap_change_percentage_24h\": 0.1666, \"source\": \"\", \"atl_date\": \"2021-12-14T21:31:35.868Z\", \"symbol\": \"zcn\", \"ath_date\": \"2021-11-10T12:21:06.184Z\", \"market_cap_change_24h\": 10327.35, \"total_volume\": 14424.28, \"ath_change_percentage\": -97.47407, \"name\": \"0chain\", \"price_change_percentage_24h\": -0.03985, \"high_24h\": 0.133511, \"market_cap\": 6209045, \"circulating_supply\": 48400982.0, \"total_supply\": 400000000.0, \"fully_diluted_valuation\": null, \"roi\": null}"]

flutter 中的代码:

类代码:

class CryptoInfo {
  final int market_cap_rank;
  final double ath;
  final double market_cap;
  final double low_24h;
  final double high_24h;
  final double current_price;
  final int total_volume;
  final String symbol;
  final String last_updated;
  final String id;
  final String image;
  final double circulating_supply;

  CryptoInfo({
    required this.market_cap_rank,
    required this.ath,
    required this.market_cap,
    required this.low_24h,
    required this.high_24h,
    required this.current_price,
    required this.total_volume,
    required this.symbol,
    required this.last_updated,
    required this.id,
    required this.image,
    required this.circulating_supply,
  });

  factory CryptoInfo.fromJson(Map<String, dynamic> json) {
    return CryptoInfo(
      market_cap_rank: json['market_cap_rank'] as int,
      ath: json['ath'] as double,
      market_cap: json['market_cap'] as double,
      low_24h: json['low_24h'] as double,
      high_24h: json['high_24h'] as double,
      current_price: json['current_price'] as double,
      total_volume: json['total_volume'] as int,
      symbol: json['symbol'] as String,
      last_updated: json['last_updated'] as String,
      id: json['id'] as String,
      image: json['image'] as String,
      circulating_supply: json['circulating_supply'] as double,
    );
  }
}

构建小部件和获取数据的代码:

class _MainPagesState extends State<MainPages> {
  static late Future<CryptoInfo> Responses;

  @override
  void initState() {
    super.initState();
    Responses = getData();
  }

  Future<CryptoInfo> getData() async {
    final response =
        await http.get(Uri.parse('http://192.168.1.24:5000/analyze'));
    final data = await jsonDecode(response.body);


    if (response.statusCode == 200) {
      print(response.statusCode);
      print(data[0]);
      final Res = CryptoInfo.fromJson(data[0]);
      print(Res.id.toString());
      return Res;
    } else {
      throw Exception('Failed to load cryptos');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("Settings"),
          centerTitle: true,
          toolbarHeight: 35,),
       body: FutureBuilder<CryptoInfo>(
        future: Responses,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Text(snapshot.data!.id);
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }

          // By default, show a loading spinner.
          return const CircularProgressIndicator();
        },
      ),
    );
  }
}

控制台输出:

I/flutter (30283): 200
I/flutter (30283): {"atl_date": "2021-12-14T21:31:35.868Z", "price_change_24h": -5.1138319612315e-05, "circulating_supply": 48400982.0, "total_supply": 400000000.0, "fully_diluted_valuation": null, "current_price": 0.128283, "max_supply": null, "roi": null, "id": "0chain", "source": "", "market_cap_rank": 987, "market_cap_change_24h": 10327.35, "ath_change_percentage": -97.47407, "last_updated": "2022-06-23T16:10:11.148Z", "atl_change_percentage": 4914281715.26934, "market_cap_change_percentage_24h": 0.1666, "atl": 2.65e-09, "symbol": "zcn", "market_cap": 6209045, "ath": 5.16, "image": "https://assets.coingecko.com/coins/images/4934/large/0_Black-svg.png?1600757954", "total_volume": 14424.28, "name": "0chain", "high_24h": 0.133511, "low_24h": 0.124866, "ath_date": "2021-11-10T12:21:06.184Z", "price_change_percentage_24h": -0.03985}
E/flutter (30283): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'Map<String, dynamic>'
E/flutter (30283): #0      _MainPagesState.getData (package:crypto_app/main.dart:116:43)
E/flutter (30283): <asynchronous suspension>
E/flutter (30283): 

如控制台所示,flutter 得到正确的数据,可以得到数据的索引 0(显示为print(data[0])。问题是将数据转换为 CryptoInfo 类,并打印出来。

【问题讨论】:

    标签: json flutter


    【解决方案1】:

    经过这么长时间,我终于找到了解决这个问题的方法。

    更新功能:

    Future<CryptoInfo> getData() async {
        final response =
            await http.get(Uri.parse('http://192.168.1.24:5000/analyze'));
        final data = await jsonDecode(response.body);
    
    
        if (response.statusCode == 200) {
          print(response.statusCode);
          print(jsonDecode(data[0])['id']);
          final Res = CryptoInfo.fromJson(jsonDecode(data[0]));
          print(Res.market_cap_rank);
          return Res;
        } else {
          throw Exception('Failed to load cryptos');
        }
    }
    

    如果您使用的是 JSON 列表,则需要再次使用 jsonDecode()。所以,这条线

    final Res = CryptoInfo.fromJson(data[0]);
    

    变成:

    final Res = CryptoInfo.fromJson(jsonDecode(data[0]));
    

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 2021-01-17
      • 2019-08-07
      • 1970-01-01
      • 2021-06-11
      • 2020-08-20
      • 1970-01-01
      • 2021-09-07
      • 2020-11-05
      相关资源
      最近更新 更多