flutter : type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

huangapple go评论74阅读模式
英文:

flutter : type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'

问题

大家好。我是新手使用Flutter。我正在制作一个UI,在其中我想使用API来显示数据,但却遇到了以下错误...

这是在UI上显示的错误截图

我不知道为什么会显示这个错误。请指导我在这里做错了什么,以便我可以修复它。

谢谢您的帮助。

以下是我想在UI上显示文本的代码

import 'package:flutter/material.dart';
import 'package:shubh_chintak/ShubhChintak/constants.dart';
import 'package:shubh_chintak/ShubhChintak/reusableWidget.dart';
import 'package:shubh_chintak/ShubhChintakGetAPI/ShubhChintakHttp/FarmerPreHarvestingGetHttp.dart';
import 'package:shubh_chintak/ShubhChintakGetAPI/ShubhChintakModelClasses/ShubhChintakModel.dart';

import 'farmerPostHarvestingCropDescription/farmerPostHarvestingCropDescription.dart';

class FarmerPostHarvesting extends StatefulWidget {
  const FarmerPostHarvesting({Key? key}) : super(key: key);

  @override
  State<FarmerPostHarvesting> createState() => _FarmerPostHarvestingState();
}

class _FarmerPostHarvestingState extends State<FarmerPostHarvesting> {
  final FarmerPreHarvestingGetHttp _farmerPreHarvestingGetHttp =
      FarmerPreHarvestingGetHttp();

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<FarmerPreHarvestingModel>>(
        future: _farmerPreHarvestingGetHttp.getPreHarvestingData(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            List<FarmerPreHarvestingModel> preHarvestingData = snapshot.data!;
            return showPreHarvestingData(context, preHarvestingData);
          } else if (snapshot.hasError) {
            return Center(
              child: Text(
                snapshot.error.toString(),
              ),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    );
  }
}

ListView showPreHarvestingData(
    BuildContext context, List<FarmerPreHarvestingModel> preHarvestingData) {
  return ListView.builder(
    itemCount: preHarvestingData.length,
    itemBuilder: (context, index) {
      return SizedBox(
        height: MediaQuery.of(context).size.height * 0.13,
        child: Card(
          shadowColor: kPrimaryColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
            side: const BorderSide(color: kPrimaryColor),
          ),
          elevation: 5,
          semanticContainer: true,          
          child: ListTile(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) =>
                      const FarmerPostHarvestingCropDescription(),
                ),
              );
            },
            title: reusableText(
                "${preHarvestingData[index].cropName}", 20, TextAlign.start),
            subtitle: reusableText(
                "${preHarvestingData[index].cropArea}", 15, TextAlign.start),
            trailing: reusableText(
                "${preHarvestingData[index].cropInitialCosting}",
                20,
                TextAlign.end),
          ),
        ),
      );
    },
  );
}

这是用于API的FarmerPreHarvestingGetHttp.dart文件的代码

import 'dart:convert';

import 'package:http/http.dart';
import 'package:shubh_chintak/ShubhChintakGetAPI/ShubhChintakModelClasses/ShubhChintakModel.dart';

class FarmerPreHarvestingGetHttp {
  final String baseUrl =
      "http://shubhchintak.digicommunique.com/Registration.asmx/ShowGetData";

  Future<List<FarmerPreHarvestingModel>> getPreHarvestingData() async {
    Response res = await get(Uri.parse(baseUrl));
    if (res.statusCode == 200) {
      List<dynamic> data = jsonDecode(res.body);
      List<FarmerPreHarvestingModel> preHarvestingData = data
          .map((dynamic item) => FarmerPreHarvestingModel.fromJson(item))
          .toList();
      return preHarvestingData;
    } else {
      throw "Something went wrong";
    }
  }
}

这是API的模型类,即ShubhChintakModel.dart文件。

class FarmerPreHarvestingModel {
  int? cropId;
  String? cropName;
  String? cropArea;
  String? cropInitialCosting;

  FarmerPreHarvestingModel({
    this.cropId,
    this.cropName,
    this.cropArea,
    this.cropInitialCosting,
  });

  FarmerPreHarvestingModel.fromJson(Map<String, dynamic> json) {
    cropId = json['crop_id'];
    cropName = json['crop_name'];
    cropArea = json['crop_area'];
    cropInitialCosting = json['crop_initialCosting'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['crop_id'] = this.cropId;
    data['crop_name'] = this.cropName;
    data['crop_area'] = this.cropArea;
    data['crop_initialCosting'] = this.cropInitialCosting;
    return data;
  }
}

这是我迄今为止尝试的,但未能解决错误。

英文:

everyone. I am new to flutter. I am making an UI where I want to display the data with the help of the api but get stuck on the following error...

This is the screenshot of the error display on UI

I don't know why it is displaying. Please guide me what I'm doing wrong here so that I could fix it.

Thanks for the help.

Below is the code where i want to display the text on the UI

import &#39;package:flutter/material.dart&#39;;
import &#39;package:shubh_chintak/ShubhChintak/constants.dart&#39;;
import &#39;package:shubh_chintak/ShubhChintak/reusableWidget.dart&#39;;
import &#39;package:shubh_chintak/ShubhChintakGetAPI/ShubhChintakHttp/FarmerPreHarvestingGetHttp.dart&#39;;
import &#39;package:shubh_chintak/ShubhChintakGetAPI/ShubhChintakModelClasses/ShubhChintakModel.dart&#39;;
import &#39;farmerPostHarvestingCropDescription/farmerPostHarvestingCropDescription.dart&#39;;
class FarmerPostHarvesting extends StatefulWidget {
const FarmerPostHarvesting({Key? key}) : super(key: key);
@override
State&lt;FarmerPostHarvesting&gt; createState() =&gt; _FarmerPostHarvestingState();
}
class _FarmerPostHarvestingState extends State&lt;FarmerPostHarvesting&gt; {
final FarmerPreHarvestingGetHttp _farmerPreHarvestingGetHttp =
FarmerPreHarvestingGetHttp();
@override
void init() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder&lt;List&lt;FarmerPreHarvestingModel&gt;&gt;(
future: _farmerPreHarvestingGetHttp.getPreHarvestingData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List&lt;FarmerPreHarvestingModel&gt; preHarvestingData = snapshot.data!;
return showPreHarvestingData(context, preHarvestingData);
} else if (snapshot.hasError) {
return Center(
child: Text(
snapshot.error.toString(),
),
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
}
ListView showPreHarvestingData(
BuildContext context, List&lt;FarmerPreHarvestingModel&gt; preHarvestingData) {
return ListView.builder(
itemCount: preHarvestingData.length,
itemBuilder: (context, index) {
return SizedBox(
height: MediaQuery.of(context).size.height * 0.13,
child: Card(
shadowColor: kPrimaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: const BorderSide(color: kPrimaryColor),
),
elevation: 5,
semanticContainer: true,          
child: ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =&gt;
const FarmerPostHarvestingCropDescription(),
),
);
},
title: reusableText(
&quot;${preHarvestingData[index].cropName}&quot;, 20, TextAlign.start),
subtitle: reusableText(
&quot;${preHarvestingData[index].cropArea}&quot;, 15, TextAlign.start),
trailing: reusableText(
&quot;${preHarvestingData[index].cropInitialCosting}&quot;,
20,
TextAlign.end),
),
),
);
},
);
}

Here is the FarmerPreHarvestingGetHttp.dart file code for the API

import &#39;dart:convert&#39;;
import &#39;package:http/http.dart&#39;;
import &#39;package:shubh_chintak/ShubhChintakGetAPI/ShubhChintakModelClasses/ShubhChintakModel.dart&#39;;
class FarmerPreHarvestingGetHttp {
final String baseUrl =
&quot;http://shubhchintak.digicommunique.com/Registration.asmx/ShowGetData&quot;;
Future&lt;List&lt;FarmerPreHarvestingModel&gt;&gt; getPreHarvestingData() async {
Response res = await get(Uri.parse(baseUrl));
if (res.statusCode == 200) {
List&lt;dynamic&gt; data = jsonDecode(res.body);
List&lt;FarmerPreHarvestingModel&gt; preHarvestingData = data
.map((dynamic item) =&gt; FarmerPreHarvestingModel.fromJson(item))
.toList();
return preHarvestingData;
} else {
throw &quot;Something went wrong&quot;;
}
}
}

Here is the Model class of the API i.e., ShubhChintakModel.dart file.

class FarmerPreHarvestingModel {
int? cropId;
String? cropName;
String? cropArea;
String? cropInitialCosting;
FarmerPreHarvestingModel({
this.cropId,
this.cropName,
this.cropArea,
this.cropInitialCosting,
});
FarmerPreHarvestingModel.fromJson(Map&lt;String, dynamic&gt; json) {
cropId = json[&#39;crop_id&#39;];
cropName = json[&#39;crop_name&#39;];
cropArea = json[&#39;crop_area&#39;];
cropInitialCosting = json[&#39;crop_initialCosting&#39;];
}
Map&lt;String, dynamic&gt; toJson() {
final Map&lt;String, dynamic&gt; data = new Map&lt;String, dynamic&gt;();
data[&#39;crop_id&#39;] = this.cropId;
data[&#39;crop_name&#39;] = this.cropName;
data[&#39;crop_area&#39;] = this.cropArea;
data[&#39;crop_initialCosting&#39;] = this.cropInitialCosting;
return data;
}
}

This is what i had try so far, but did not able to solve the error.

答案1

得分: 0

your response are a map, and the data that you need is a list with key data

your response:

{
  "result": "Success",
  "message": "Show All Data",
  "data": [
    {
      "crop_id": 46,
      "crop_name": "Rice",
      "crop_area": "343",
      "crop_initialCosting": "10000"
    }
  ]
}

you need to get the data and serialize to your model

Workaround:

Future<List<FarmerPreHarvestingModel>> getPreHarvestingData() async {
    Response res = await get(Uri.parse(baseUrl));
    if (res.statusCode == 200) {
      final resp = jsonDecode(res.body); // this is Map
      List<dynamic> data = resp["data"]; // this is List
      List<FarmerPreHarvestingModel> preHarvestingData = data
          .map((dynamic item) => FarmerPreHarvestingModel.fromJson(item))
          .toList();
      return preHarvestingData;
    } else {
      throw "Something went wrong";
    }
}
英文:

your response are a map, and the data that you need is a list with key data

your response:

{
&quot;result&quot;: &quot;Success&quot;,
&quot;message&quot;: &quot;Show All Data&quot;,
&quot;data&quot;: [
{
&quot;crop_id&quot;: 46,
&quot;crop_name&quot;: &quot;Rice&quot;,
&quot;crop_area&quot;: &quot;343&quot;,
&quot;crop_initialCosting&quot;: &quot;10000&quot;
}
]
}

you need to get the data and serialize to your model

Workaround:

Future&lt;List&lt;FarmerPreHarvestingModel&gt;&gt; getPreHarvestingData() async {
Response res = await get(Uri.parse(baseUrl));
if (res.statusCode == 200) {
/// update here &gt;&gt;&gt;&gt;&gt;&gt;&gt;
final resp = jsonDecode(res.body); // this is Map
List&lt;dynamic&gt; data = resp[&quot;data&quot;]; // this is List
List&lt;FarmerPreHarvestingModel&gt; preHarvestingData = data
.map((dynamic item) =&gt; FarmerPreHarvestingModel.fromJson(item))
.toList();
return preHarvestingData;
} else {
throw &quot;Something went wrong&quot;;
}
}

huangapple
  • 本文由 发表于 2023年3月9日 14:37:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定