【发布时间】:2020-12-09 01:10:04
【问题描述】:
我正在尝试从 json 创建一个列表,但它向我抛出了错误:“列表不是 Map
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(...)的地方。但每次都不容易看到。