首页 > 解决方案 > “产品”类型的值不能分配给“列表”类型的变量'

问题描述

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Future<List<Products>> getApiData() async {
    var url = "https://gorest.co.in/public-api/products";
    var response = await http.get(url);
    var jsonString = response.body;
    List<Products> products = productsFromJson(jsonString);
    
    print(jsonString);
    return products;   
    
  }

为什么它不起作用,[“产品”类型的值不能分配给“列表”类型的变量。尝试更改变量的类型,或将右侧类型转换为“列表”。;][1]

  [1]: https://i.stack.imgur.com/MQCEP.png

json 到 dart 文件
“产品”类型的值不能分配给“列表”类型的变量。尝试改变变量的类型,dart(invalid_assignment)

Products productsFromJson(String str) => 
Products.fromJson(json.decode(str));
String productsToJson(Products data) => json.encode(data.toJson());
class Products {
  Products({
    this.code,
    this.meta,
    this.data,
  });
  int code;
  Meta meta;
  List<Datum> data;

  factory Products.fromJson(Map<String, dynamic> json) => Products(
        code: json["code"],
        meta: Meta.fromJson(json["meta"]),
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "code": code,
        "meta": meta.toJson(),
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}
class Datum {
  Datum({
    this.id,
    this.name,
    this.description,
    this.image,
    this.price,
    this.discountAmount,
    this.status,
    this.categories,
  });
  int id;
  String name;
  String description;
  String image;
  String price;
  String discountAmount;
  bool status;
  List<Category> categories;

标签: flutterdart

解决方案


var url = "https://gorest.co.in/public-api/products";
var response = await http.get(url);
var jsonString = jsonDecode(response.body);
List<Products> products = jsonString.map((jsonMap) => Products.fromJson(jsonMap)).toList();

如果您需要将所有产品作为列表返回,您可以这样使用。


推荐阅读