【问题标题】:Error parsing list of products in dart flutter using http使用http解析飞镖颤振中的产品列表时出错
【发布时间】:2021-08-22 23:03:03
【问题描述】:

我有一个 api,我想从中解析一些数据,我有一个将数据转换为 dart 模型类的插件,但是每当我尝试获取响应时,如果有人可以提供帮助,它会一直显示错误,将不胜感激

  • 这是api链接
 https://fakestoreapi.com/products/category/electronics 
  • 这是模型类(使用 dart 插件生成)

class ProductsModel {
    String category;
    String description;
    int id;
    String image;
    double price;
    String title;

    ProductsModel({this.category, this.description, this.id, this.image, this.price, this.title});

    factory ProductsModel.fromJson(Map<String, dynamic> json) {
        return ProductsModel(
            category: json['category'], 
            description: json['description'], 
            id: json['id'], 
            image: json['image'], 
            price: json['price'], 
            title: json['title'], 
        );
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['category'] = this.category;
        data['description'] = this.description;
        data['id'] = this.id;
        data['image'] = this.image;
        data['price'] = this.price;
        data['title'] = this.title;
        return data;
    }
}

  • 这就是我解析数据的方式
void main(){
  runApp(MaterialApp(
    home: FirstScreenApp(),
    debugShowCheckedModeBanner: false,
  ));
}

class FirstScreenApp extends StatefulWidget {
  @override
  _FirstScreenAppState createState() => _FirstScreenAppState();
}

class _FirstScreenAppState extends State<FirstScreenApp> {

  Future<ProductsModel> _getElectronics() async {
    var url = "https://fakestoreapi.com/products/category/electronics";
    var response = await http.get(Uri.parse(url));
    if(response.statusCode == 200){
      // success
      var decodedResponse = json.decode(response.body);
      return ProductsModel.fromJson(decodedResponse);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       body: FutureBuilder<ProductsModel>(
         future: _getElectronics(),
         builder: (context,data){
           if(data.hasError){
             return Center(
               child: Text("Error " + data.error.toString()),
             );
           }
           if(data.connectionState == ConnectionState.done){
             return ListView.builder(
               itemCount: 4 ,
               itemBuilder: (context,index){
                 return Container(
                   margin: const EdgeInsets.all(10),
                   child: Card(
                     elevation: 10,
                     child: Padding(
                       padding: const EdgeInsets.all(12.0),
                       child: Row(
                         children: [
                           Image.network(data.data.image),
                           SizedBox(height: 10,),
                           Column(
                             mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                             crossAxisAlignment: CrossAxisAlignment.start,
                             children: [
                               Text("League : " + data.data.title),
                               Text("Sport : " + data.data.category),
                               Text("DP : " + data.data.price.toString())
                             ],
                           ),
                         ],
                       )
                     ),
                   ),
                 );
               },
             );
           }
           return Center(
             child: CircularProgressIndicator(),
           );
         },
       ),
    );
  }
}

 * This is the error generated

type 'List 不是 >' 类型的子类型



【问题讨论】:

  • API 响应有超过 1 个产品。这是一个列表。
  • 当我返回一个列表时,它也显示一个错误,插件应该生成一个包含产品列表的类,但是两个插件做了同样的事情我很困惑

标签: flutter http dart


【解决方案1】:

您可以通过以下方式获取 JSON 列表。

 Future<List<ProductsModel>> _getElectronics() async {
    var url = "https://fakestoreapi.com/products/category/electronics";
    var response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      // success
      List decodedResponse = json.decode(response.body);

   
      return decodedResponse
          .map((data) => ProductsModel.fromJson(data))
          .toList();
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load data');
    }
  }

您可以复制粘贴我的代码并感谢我。

 import 'dart:convert';

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

class FirstScreenApp extends StatefulWidget {
  @override
  _FirstScreenAppState createState() => _FirstScreenAppState();
}

class _FirstScreenAppState extends State<FirstScreenApp> {
  Future<List<ProductsModel>>? loadedData;
  Future<List<ProductsModel>> _getElectronics() async {
    var url = "https://fakestoreapi.com/products/category/electronics";
    var response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      // success
      List decodedResponse = json.decode(response.body);

      // var d=decodedResponse.map((data) => ProductsModel.fromJson(data)).toList();
      print(decodedResponse[1]);
      return decodedResponse
          .map((data) => ProductsModel.fromJson(data))
          .toList();
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load data');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    loadedData = _getElectronics();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<List<ProductsModel>>(

        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(
              child: Text("Error " + snapshot.error.toString()),
            );
          }
          if (snapshot.connectionState == ConnectionState.done) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                return Container(
                  margin: const EdgeInsets.all(10),
                  child: Card(
                    elevation: 10,
                    child: Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Row(
                          children: [
                            Image.network(snapshot.data![index].image!),
                            SizedBox(
                              height: 10,
                            ),
                            Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                    "League : " + snapshot.data![index].title!),
                                Text("Sport : " +
                                    snapshot.data![index].category!),
                                Text("DP :  ${snapshot.data![index].price!} ")
                              ],
                            ),
                          ],
                        )),
                  ),
                );
              },
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
        future: loadedData,
      ),
    );
  }
}

这是你的模型类

class ProductsModel {
  final category;
  final description;
  final id;
  final image;
  final price;
  final title;

  ProductsModel(
      {this.category,
      this.description,
      this.id,
      this.image,
      this.price,
      this.title});

  factory ProductsModel.fromJson(Map<String, dynamic> json) {
    return ProductsModel(
      id: json['id'],
      title: json['title'],
      price: json['price'],
      description: json['description'],
      category: json['category'],
      image: json['image'],
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['category'] = this.category;
    data['description'] = this.description;
    data['id'] = this.id;
    data['image'] = this.image;
    data['price'] = this.price;
    data['title'] = this.title;
    return data;
  }
}

【讨论】:

  • 它成功了,谢谢,无论如何我们为什么需要映射数据然后将其转换为列表,谢谢!
  • ProductsModel 是一张地图,我们需要多个 ProductsModels
  • 我们实际上需要 List 这意味着地图列表
猜你喜欢
  • 2023-03-05
  • 2020-09-12
  • 1970-01-01
  • 2020-05-19
  • 2019-10-21
  • 2021-01-24
  • 2021-03-06
  • 2020-08-12
  • 1970-01-01
相关资源
最近更新 更多