当前位置: 首页 > 知识库问答 >
问题:

类_InternalLinkedHashMap没有具有匹配参数的实例方法map。(颤动)

程正阳
2023-03-14

我是编程界的新手,我从很多方面研究过这个错误,但我什么也没发现。我正在尝试构建一个ListView。Flatter中的生成器,其中itemBuilder来自我的JSON响应数据,如下所示:

{
  "status": "success",
  "data": {
    "general": [
      {
        "id": 1,
        "name": "Sumbangan Pembinaan Pendidikan",
        "icon": "credit_card",
        "type": "monthly",
        "amount": 125000
      },
      {
        "id": 2,
        "name": "Uang Bangunan",
        "icon": "credit_card",
        "type": "yearly",
        "amount": 1250000
      }
    ],
    "categorized": [
      {
        "name": "Bayar Buku",
        "icon": "credit_card",
        "childs": [
          {
            "id": 3,
            "name": "Buku 1",
            "icon": "credit_card",
            "type": "monthly",
            "amount": 324423
          },
          {
            "id": 4,
            "name": "Buku 2",
            "icon": "credit_card",
            "type": "monthly",
            "amount": 16000
          }
        ]
      }
    ]
  }
}

我需要获取要使用ListView获取的项的“名称”。建筑工人,这就是我想到的

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:sekolah_kita/components/constant.dart';
import 'package:http/http.dart' as http;
import 'package:sekolah_kita/components/storage.dart';

class DaftarTransaksi extends StatefulWidget {
  @override
  _DaftarTransaksiState createState() => _DaftarTransaksiState();
}

class _DaftarTransaksiState extends State<DaftarTransaksi> {
  final SecureStorage secureStorage = SecureStorage();

  List studentFeesData;

  bool isLoading = true;

  @override
  void initState() {
    secureStorage.readSecureData('student_token').then((value) {
      getStudentFees(
        value,
      );
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: secondaryColor,
      appBar: AppBar(
        leading: IconButton(
          onPressed: (){
            Navigator.pop(context);
          },
          icon: Icon(
            Icons.arrow_back
          ),
        ),
        backgroundColor: primaryColor,
        elevation: 0,
        centerTitle: true,
        title: Text(
          'Transaksi',
          style: TextStyle(
            fontSize: screenWidth(context)*(1/25),
          ),
        ),
      ),
      body: isLoading ? Center(
        child: CircularProgressIndicator(
          backgroundColor: primaryColor,
        ),
      ) : Center(
        child: Container(
          margin: EdgeInsets.symmetric(
            vertical: screenHeight(context)*(1/30),
            horizontal: screenWidth(context)*(1/20),
          ),
          color: Colors.green.withOpacity(0.5),
          child: ListView.builder(
            itemCount: studentFeesData == 0 ? 0 : studentFeesData.length,
            itemBuilder: (context, index){
              return studentFeeButtonMenu(
                context, 
                studentFeesData[index]['data']['general']['name'], 
                Icons.credit_card);
            },
          ),
        ),
      ),
    );
  }

  Future<String> getStudentFees(String token) async{
    var uri = Uri.https('sekolahkita.zonaku.com', '/api/school-fee/bill');
    http.Response response = await http.get(
      uri,
      headers: {
        HttpHeaders.contentTypeHeader: 'application/json',
        HttpHeaders.acceptHeader: 'application/json',
        HttpHeaders.authorizationHeader: "Bearer "+token,
      },
    );
    var data = json.decode(response.body);
    studentFeesData = List<dynamic>.from(
      data.map<dynamic>(
        (dynamic item) => item,
      )
    );
  }

  Widget studentFeeButtonMenu(BuildContext context, String text, IconData iconFee){
    return Container(
      width: double.infinity,
      height: screenHeight(context)*(1/12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Center(
        child: Container(
          width: screenWidth(context)*(1/1.3),
          height: double.infinity,
          color: Colors.red,
          child: Row(
            children: [
              Icon(
                iconFee,
                color: Color(0xff84923f),
              ),
              SizedBox(
                width: screenWidth(context)*(1/10),
              ),
              Text(
                text,
                style: TextStyle(
                  color: Colors.black,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

}

但在ListView中显示所需内容时,总是会出现错误。建设者我的JSON响应的运行时类型是“\u InternalLinkedHashMap”

这是我的错误消息:

已发生异常。类_InternalLinkedHashMap

我希望任何人都能帮助我。

共有1个答案

徐峰
2023-03-14

您需要将json数据转换为模型对象,以便于访问。我已将您的json数据转换如下:

StudentFeesModel
GeneralModel
CategorizedModel

现在,您可以访问

以下是片段:

import 'dart:convert';

void main() {
  dynamic data = {
    "status": "success",
    "data": {
      "general": [
        {
          "id": 1,
          "name": "Sumbangan Pembinaan Pendidikan",
          "icon": "credit_card",
          "type": "monthly",
          "amount": 125000
        },
        {
          "id": 2,
          "name": "Uang Bangunan",
          "icon": "credit_card",
          "type": "yearly",
          "amount": 1250000
        }
      ],
      "categorized": [
        {
          "name": "Bayar Buku",
          "icon": "credit_card",
          "childs": [
            {
              "id": 3,
              "name": "Buku 1",
              "icon": "credit_card",
              "type": "monthly",
              "amount": 324423
            },
            {
              "id": 4,
              "name": "Buku 2",
              "icon": "credit_card",
              "type": "monthly",
              "amount": 16000
            }
          ]
        }
      ]
    }
  };

  // NOTE: You just need to pass data instead of data["data"] i.e,
  // You should write the following:
  // StudentFeesModel studentFeesData = StudentFeesModel.fromJson(data);
  StudentFeesModel studentFeesData = StudentFeesModel.fromJson(data["data"]);
  
  List generalNames = studentFeesData.general.map((generalModel) => generalModel.name).toList();
  List categorizedNames = studentFeesData.categorized.map((categorizedModel) => categorizedModel.name).toList();
  
  print("General names: " + generalNames.toString());
  print("Categorized names: " + categorizedNames.toString());
  
  // If you want categorized child names, then
  // Iterate over all categorized objects & add all child names to a single list
  
  List categorizedChildNames = [];
  for(dynamic categorized in studentFeesData.categorized) {
    categorizedChildNames.addAll(categorized.childs.map((childObject) => childObject.name).toList());
  }
  
  print("Categorized child names: " + categorizedChildNames.toString());
}

// **************************
// Model classes
// **************************
class StudentFeesModel {
  StudentFeesModel({
    this.general,
    this.categorized,
  });

  final List<dynamic> general, categorized;

  factory StudentFeesModel.fromJson(dynamic json) {
    return StudentFeesModel(
      general: GeneralModel.listOfGeneralModel(json["general"]),
      categorized: CategorizedModel.listOfCategorizedModel(json["categorized"]),
    );
  }
  
  dynamic toJson() => {
    "general": general,
    "categorized": categorized,
  };
  
  @override
  String toString() {
    return '${JsonEncoder.withIndent(' ').convert(this)}';
  }
}

class GeneralModel {
  GeneralModel({
    this.id,
    this.name,
    this.icon,
    this.type,
    this.amount,
  });

  final int id, amount;
  final String name, icon, type;

  factory GeneralModel.fromJson(dynamic json) {
    if (json == null) return null;

    return GeneralModel(
      id: json["id"],
      name: json["name"],
      icon: json["icon"],
      type: json["type"],
      amount: json["amount"],
    );
  }

  static List<dynamic> listOfGeneralModel(dynamic list) {
    if (list == null) return null;

    dynamic generalModelList = [];
    for (dynamic json in list) {
      generalModelList.add(GeneralModel.fromJson(json));
    }

    return generalModelList;
  }
  
  dynamic toJson() => {
    "id": id,
    "name": name,
    "icon": icon,
    "type": type,
    "amount": amount,
  };
  
  @override
  String toString() {
    return '${JsonEncoder.withIndent(' ').convert(this)}';
  }
}

class CategorizedModel {
  CategorizedModel({
    this.name,
    this.icon,
    this.childs, // children would be more appropriate
  });

  final String name, icon;
  final List<dynamic> childs; // children would be more appropriate

  factory CategorizedModel.fromJson(dynamic json) {
    return CategorizedModel(
      name: json["name"],
      icon: json["icon"],
      childs: GeneralModel.listOfGeneralModel(json["childs"]), // children would be more appropriate
    );
  }

  static List<dynamic> listOfCategorizedModel(List<dynamic> list) {
    if (list == null) return null;

    List categorizedModelList = [];
    for (dynamic json in list) {
      categorizedModelList.add(CategorizedModel.fromJson(json));
    }
    
    return categorizedModelList;
  }
  
  dynamic toJson() => {
    "name": name,
    "icon": icon,
    "childs": childs,
  };
  
  @override
  String toString() {
    return '${JsonEncoder.withIndent(' ').convert(this)}';
  }
}
 类似资料:
  • 这是我的错误行: 这是我的代码:

  • 我对flatter/Dart还是有点陌生,我从php json文件中恢复了数据,但它在flatter中显示了一个错误。

  • 本文向大家介绍Scala没有参数的实例化类:{} vs(),包括了Scala没有参数的实例化类:{} vs()的使用技巧和注意事项,需要的朋友参考一下 示例 假设我们有一个MyClass类,没有构造函数参数: 在Scala中,我们可以使用以下语法实例化它: 或者我们可以简单地写: 但是,如果不注意,在某些情况下,可选的括号可能会产生某些意外的行为。假设我们要创建一个任务,该任务应在单独的线程中运行

  • 我有一个应用程序,我想从Firestore数据库中检索uid文档中表示的消息,如下所述,这些消息存储如下:聊天室- 但我收到以下错误: 生成StreamBuilder时引发了以下NoSuchMethodError(脏,状态:\u StreamBuilderBaseState 导致错误的相关小部件是:StreamBuilderfile:///Users/ahmedhussain/Downloads/

  • 查看std:make_sharedvs std::shared_ptr的前一个堆栈问题,我试图在一个uni项目中实现它。这是之前的“问题”: 我想不出有什么情况

  • 问题内容: 我对包含不带参数的泛型方法的代码感到困惑,所以这种方法的返回泛型类型是什么,例如: 这是通过以下方式调用的: 接口定义为: 我的问题:是否接受字符串,对象和所有内容。那么什么时候将通用返回类型指定为String呢? 问题答案: 编译器从 LHS 分配中使用的具体类型推断出类型。 从此链接: 如果类型参数未出现在方法参数的类型中,则编译器无法通过检查实际方法参数的类型来推断类型参数。如果