You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用API报错:_InternalLinkedHashMap无'code' getter的解决方法

问题:调用API时出现Class '_InternalLinkedHashMap<String, dynamic>' has no instance getter 'code'错误

错误原因

你的Hisselist类中,result字段被定义为List<dynamic>,解析JSON时仅直接存储原始Map数据,未转换为ResultClass实例。页面中尝试访问hisseResult?.result[index].code时,实际是在访问_InternalLinkedHashMap对象的code属性,而Map本身没有这个getter,因此触发报错。

修复步骤

1. 修改Hisselist模型类

将result类型从List<dynamic>改为List<ResultClass>,并在fromJson方法中将每个JSON对象转换为ResultClass实例:

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; // 修正为List<ResultClass>类型

  factory Hisselist.fromJson(Map<String, dynamic> json) => Hisselist(
    success: json["success"],
    // 将每个JSON元素转换为ResultClass实例
    result: List<ResultClass>.from(json["result"].map((x) => ResultClass.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "success": success,
    "result": List<dynamic>.from(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: json["rate"].toDouble(),
    lastprice: json["lastprice"].toDouble(),
    lastpricestr: json["lastpricestr"],
    hacim: json["hacim"].toDouble(),
    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,
  };
}

2. 优化页面代码(可选)

移除单独的counter变量,直接通过hisseResult?.result.length获取列表长度,同时修正一处语法错误:

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');
  Hisselist? hisseResult;

  Future callHisse() async {
    try{
      Map<String, String> requestHeaders = {
        'Content-Type': 'application/json',
        'Authorization': 'xxx'
      };
      final response = await http.get(url,headers:requestHeaders);

      if(response.statusCode == 200){
        var result = hisselistFromJson(response.body);

        if(mounted) { // 修正原代码中多余的分号
          setState(() {
            hisseResult = result;
          });
        }
        return result;
      } else {
        print(response.statusCode);
      }
    } catch(e) {
      print(e.toString());
    }
  }
  
  @override
  void initState() {
    super.initState();
    callHisse();
  }
  
  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        automaticallyImplyLeading: false,
        title: const Text('Hisseler'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: hisseResult != null ?
          ListView.builder(
              itemCount: hisseResult!.result.length,
              itemBuilder: (context, index){
                final stockItem = hisseResult!.result[index];
                return Card(
                  child: ListTile(
                    title: Text(stockItem.code),
                    subtitle: Text(stockItem.text), // 替换重复的code为text,更符合展示逻辑
                  ),
                );
          }) : const Center(child: CircularProgressIndicator()),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

内容的提问来源于stack exchange,提问作者Mıktad Tahir Durak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:33:47