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

类型“List”不是颤振应用程序中“Map

薛弘济
2023-03-14

我试图在Flutter中创建一个API请求,但我得到以下错误作为响应

类型'列表

我试图创建第一个API,请让我知道,如果方法是好的

这是我的密码

import 'package:flutter/material.dart';

class Product {
  final int id;
  final String title, description;
  final String images;
  final List<Color> colors;
  final double price;
  final double rating;
  final bool isFavourite, isPopular;

  Product(
      {this.id,
      this.images,
      this.colors,
      this.title,
      this.price,
      this.rating,
      this.description,
      this.isFavourite,
      this.isPopular});
  factory Product.fromJson(Map<String, dynamic> json) {
    return Product(
      id: json['id'],
      images: json['images'],
      title: json['title'],
      price: json['price'],
      rating: json['rating'],
      description: json['description'],
    );
  }
}


Future<Product> fetchProd() async {
  final response = await http.get('https://test.com/sampleapi.php');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Product.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

class ProdList extends StatefulWidget {
  @override
  _ProdListState createState() => _ProdListState();
}

class _ProdListState extends State<ProdList> {
  Future<Product> futureProdLists;
  @override
  void initState() {
    super.initState();
    futureProdLists = fetchProd();
  
  }

 

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Padding(
        padding:
            EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(20)),
        child: SectionTitle(title: "Popular Products", press: () {}),
      ),
      SizedBox(height: getProportionateScreenWidth(20)),
      SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: FutureBuilder<Product>(
          future: futureProdLists,
          builder: (context, snapshot) {
            print(snapshot);
            if (snapshot.hasData) {
              return Text(snapshot.data.title);
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }

这是我的示例API

[
  {
    "id": "0001",
    "images": "assets/images/ps4_console_white_1.png",
    "title": "Wireless Controller for PS4",
    "price": 25,
    "description": "description",
    "rating": 4.8,
    "rating (copy)": 4.8,
    "isFavourite": true,
    "isPopular": true
  },
  {
    "id": "0001",
    "images": "assets/images/ps4_console_white_1.png",
    "title": "Wireless Controller for PS4",
    "price": 25,
    "description": "description",
    "rating": 4.8,
    "rating (copy)": 4.8,
    "isFavourite": true,
    "isPopular": true
  },
  {
    "id": "0001",
    "images": "assets/images/ps4_console_white_1.png",
    "title": "Wireless Controller for PS4",
    "price": 25,
    "description": "description",
    "rating": 4.8,
    "rating (copy)": 4.8,
    "isFavourite": true,
    "isPopular": true
  },
  {
    "id": "0001",
    "images": "assets/images/ps4_console_white_1.png",
    "title": "Wireless Controller for PS4",
    "price": 25,
    "description": "description",
    "rating": 4.8,
    "rating (copy)": 4.8,
    "isFavourite": true,
    "isPopular": true
  },
  {
    "id": "0001",
    "images": "assets/images/ps4_console_white_1.png",
    "title": "Wireless Controller for PS4",
    "price": 25,
    "description": "description",
    "rating": 4.8,
    "rating (copy)": 4.8,
    "isFavourite": true,
    "isPopular": true
  }
]

共有3个答案

焦兴为
2023-03-14

这肯定会奏效<代码>最终产品产品=productFromJson(jsonString)


import 'dart:convert';

List<Product> productFromJson(String str) => List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));

String productToJson(List<Product> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Product {
    Product({
        this.id,
        this.images,
        this.title,
        this.price,
        this.description,
        this.rating,
        this.ratingCopy,
        this.isFavourite,
        this.isPopular,
    });

    String id;
    String images;
    String title;
    int price;
    String description;
    double rating;
    double ratingCopy;
    bool isFavourite;
    bool isPopular;

    factory Product.fromJson(Map<String, dynamic> json) => Product(
        id: json["id"],
        images: json["images"],
        title: json["title"],
        price: json["price"],
        description: json["description"],
        rating: json["rating"].toDouble(),
        ratingCopy: json["rating (copy)"].toDouble(),
        isFavourite: json["isFavourite"],
        isPopular: json["isPopular"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "images": images,
        "title": title,
        "price": price,
        "description": description,
        "rating": rating,
        "rating (copy)": ratingCopy,
        "isFavourite": isFavourite,
        "isPopular": isPopular,
    };
}
法池暝
2023-03-14

试试这个

Future<Product> fetchProd() async {
  final response = await http.get('https://test.com/sampleapi.php');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return (response.body as List)
      .map((item) => Product.fromJson(item))
      .toList();
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
颜云瀚
2023-03-14

问题是您的api响应提供了产品对象的json数组,您正试图将该数组转换为产品对象,这就是问题所在。

现在,您必须迭代json数组,将每个元素转换为产品对象,并将它们存储在列表中。

用下面的代码片段替换fetchProd方法。

Future<List<Product>> fetchProd() async {
  List<Product> prodList = [];

  final response = await http.get('https://test.com/sampleapi.php');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    var jsonList = jsonDecode(response.body);
    for(var prod in jsonList){
      prodList.add(Product.fromJson(prod));
    }
    return prodList;
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
 类似资料: