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

未处理的异常:当从jsonplaceholder.typecode.com/photos获取Json时,类型列表不是类型映射的子类型

艾才良
2023-03-14

我正在尝试从中获取JSONhttps://jsonplaceholder.typicode.com/photos/但获取类似未处理异常的错误:类型“List”不是类型“Map”的子类型

有办法吗?

这是我的代码。

主要的飞奔

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'src/widgets/image_list.dart';
import 'src/models/imageloader.dart';

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "app",
      theme: ThemeData(primarySwatch: Colors.blue),
      home: homePage(),
    );
  }
}

class homePage extends StatefulWidget {
  @override
  _homePageState createState() => _homePageState();
}

class _homePageState extends State<homePage> {
  int counter = 0;
  List<ImageLoader> images = [];
  void loadImage() async {
    counter++;
    var response =
        await get(Uri.parse('https://jsonplaceholder.typicode.com/photos/'));
    var imageModel = ImageLoader.fromJson(jsonDecode(response.body));
    /*  var imagemodel = imageModel.map((i) => ImageLoader.fromJson(i)).toList(); */
    setState(() {
      images.add(imageModel);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Let's load some images"),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: loadImage,
        child: Icon(Icons.add),
      ),
      body: ImageList(images),
    );
  }
}

影印机。飞奔

class ImageLoader {
  int id = 0;
  String url = "";
  String title = "";

  ImageLoader(this.id, this.url, this.title);

  ImageLoader.fromJson(Map<String, dynamic> parsedJson) {
    id = parsedJson['id'];
    url = parsedJson['url'];
    title = parsedJson['title'];
  }
}

image_list.dart

import 'package:flutter/material.dart';
import '../models/imageloader.dart';

class ImageList extends StatelessWidget {
  final List<ImageLoader> images;
  ImageList(
    this.images,
  );

  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: images.length,
      itemBuilder: (context, int index) {
        return Text(images[index].url);
      },
    );
  }
}

调试控制台:

未处理的异常:类型列表不是类型映射的子类型

共有1个答案

田成仁
2023-03-14

您的响应出现在一个列表中,其中包含您想要的地图。在您的var响应行下使用此选项,它应该可以工作:


List<ImageLoader> _images = [];
var decodedResponse = jsonDecode(response.body);

for (var item in decodedResponse) {
_images.add(ImageLoader.fromJson(item));
}

setState(() {
      images= _images;
    });
 类似资料: