【问题标题】:Create list throws List<dynamic> is not subtype of type Map<string, dynamic>创建列表抛出 List<dynamic> 不是 Map<string, dynamic> 类型的子类型
【发布时间】:2020-12-09 01:10:04
【问题描述】:

我正在尝试从 json 创建一个列表,但它向我抛出了错误:“列表不是 Map 类型的子类型”。 代码的第一部分是我尝试创建列表 b 的位置,该列表位于调用主窗口小部件的窗口小部件中。在第二个代码块中,我执行获取并接收端点,然后返回响应并返回最后一个是json的结构。

 import 'package:flutter/material.dart';
 import 'package:eshop/models/products.dart';
 import 'package:eshop/function/fetch.dart';
 
 const endPoint = 'https://sistemas.cruzperez.com/flutter/jsonPrueba.json';
 
 class HomePage extends StatefulWidget {
   @override
   _HomePageState createState() => _HomePageState();
 }
 
 class _HomePageState extends State<HomePage> {
    
   Future<Product> futureProduct;
   @override
   void initState() { 
     super.initState();
      futureProduct = getData(endPoint);
      
   }
 
   @override
   Widget build(BuildContext context) {
     return Scaffold(
       appBar:AppBar(
         title: Text('Eshop'),
         automaticallyImplyLeading: false,
         actions: <Widget>[
           IconButton(icon: Icon(Icons.shopping_cart, color: Colors.white), onPressed: (){})
         ],
       ),
       body: Center(  
         child: Container(
           child: Column(
             children: <Widget>[
               listJson(futureProduct)
             ],
           ),
         )
       ),
     );
   }
 }

 
         
 Widget listJson(futureProduct){
   return Container(
       child: FutureBuilder<Product>(
         future: futureProduct,
         builder: (context, snapshot){
           if(snapshot.hasData){
             return Text(snapshot.data.nombre);
           }else if(snapshot.hasError){
             return Text("${snapshot.error}");
           }
             return CircularProgressIndicator();
         },
       ),
   );
 }
 import 'dart:async';
 import 'package:http/http.dart' as http;
 import 'package:eshop/models/products.dart';
 
 Future<Product> getData(endPoint) async{
     final response = await http.get(endPoint);
     if (response.statusCode == 200) {
       return Product.fromJson(json.decode(response.body));
     }else{
       throw Exception('Error a cargar json');
     }
   }
class Product{
  final int idSucursal;
  final int idProducto;
  final String nombre;
  final String categoria;
  final int precio;
  final int disponible;
  final String descripcion;
  final String imgUrl;
  
  Product({
    this.idSucursal,
    this.idProducto,
    this.nombre,
    this.categoria,
    this.precio,
    this.disponible,
    this.descripcion,
    this.imgUrl
  });

  factory Product.fromJson(Map<String, dynamic> json){
    return Product(
      idSucursal: json['id_sucursal'],
      idProducto: json['id_producto'],
      nombre: json['nombre'],
      categoria: json['categoria'],
      precio: json['precio'],
      disponible: json['disponible'],
      descripcion: json['descripcion'],
      imgUrl: json['img_url'],
    );
  }
}

【问题讨论】:

  • 请提供您收到的json。我假设它看起来以 [ 开头,表示列表的开头。
  • 还有下次:请提供引发错误的具体行。这是写return Product.fromJson(...) 的地方。但每次都不容易看到。

标签: json flutter dart


【解决方案1】:

您可以在下面复制粘贴运行完整代码
第1步:你需要使用List&lt;Product&gt;并用productFromJson解析

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

第二步:你可以用ListView显示数据

return ListView.builder(
          shrinkWrap: true,
          itemCount: snapshot.data.length,
          itemBuilder: (context, index) {
            return Card(
                elevation: 6.0,
                child: Padding(
                  padding: const EdgeInsets.only(
                      top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(snapshot.data[index].nombre.toString()),
                    ],
                  ),
                ));

工作演示

完整代码

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
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.idSucrsal,
    this.idProducto,
    this.nombre,
    this.categoria,
    this.precio,
    this.disponible,
    this.descripcion,
    this.imgUrl,
  });

  int idSucrsal;
  int idProducto;
  String nombre;
  Categoria categoria;
  int precio;
  int disponible;
  String descripcion;
  String imgUrl;

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        idSucrsal: json["id_sucrsal"],
        idProducto: json["id_producto"],
        nombre: json["nombre"],
        categoria: categoriaValues.map[json["categoria"]],
        precio: json["precio"],
        disponible: json["disponible"],
        descripcion: json["descripcion"],
        imgUrl: json["img_url"],
      );

  Map<String, dynamic> toJson() => {
        "id_sucrsal": idSucrsal,
        "id_producto": idProducto,
        "nombre": nombre,
        "categoria": categoriaValues.reverse[categoria],
        "precio": precio,
        "disponible": disponible,
        "descripcion": descripcion,
        "img_url": imgUrl,
      };
}

enum Categoria { RES, CERDO, EMBUTIDO }

final categoriaValues = EnumValues({
  "cerdo": Categoria.CERDO,
  "embutido": Categoria.EMBUTIDO,
  "res": Categoria.RES
});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

const endPoint = 'https://sistemas.cruzperez.com/flutter/jsonPrueba.json';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<List<Product>> futureProduct;

  Future<List<Product>> getData(endPoint) async {
    final response = await http.get(endPoint);
    if (response.statusCode == 200) {
      return productFromJson(response.body);
    } else {
      throw Exception('Error a cargar json');
    }
  }

  @override
  void initState() {
    super.initState();
    futureProduct = getData(endPoint);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Eshop'),
        automaticallyImplyLeading: false,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.shopping_cart, color: Colors.white),
              onPressed: () {})
        ],
      ),
      body: Center(
          child: Container(
        child: Column(
          children: <Widget>[Expanded(child: listJson(futureProduct))],
        ),
      )),
    );
  }
}

Widget listJson(futureProduct) {
  return Container(
    child: FutureBuilder<List<Product>>(
      future: futureProduct,
      builder: (context, AsyncSnapshot<List<Product>> snapshot) {
        switch (snapshot.connectionState) {
          case ConnectionState.none:
            return Text('none');
          case ConnectionState.waiting:
            return Center(child: CircularProgressIndicator());
          case ConnectionState.active:
            return Text('');
          case ConnectionState.done:
            if (snapshot.hasError) {
              return Text(
                '${snapshot.error}',
                style: TextStyle(color: Colors.red),
              );
            } else {
              return ListView.builder(
                  shrinkWrap: true,
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return Card(
                        elevation: 6.0,
                        child: Padding(
                          padding: const EdgeInsets.only(
                              top: 6.0, bottom: 6.0, left: 8.0, right: 8.0),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(snapshot.data[index].nombre.toString()),
                            ],
                          ),
                        ));
                  });
            }
        }
      },
    ),
  );
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2023-01-08
    • 2019-04-03
    • 1970-01-01
    • 2021-10-25
    • 2020-07-03
    • 2019-12-05
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多