【问题标题】:Access list within the Model class of Json file in FlutterFlutter中Json文件的Model类内的访问列表
【发布时间】:2021-08-29 07:32:47
【问题描述】:

我正在尝试从主屏幕访问我的 bean 类中的列表。为从 API 中提取 JSON 数据而创建的 Bean 类。我的 bean 类是汽车,我从名为“datalist”的列表中获取数据,该列表是 JSON 数据中的另一个列表。但我收到运行时错误,因为“无效值:有效值范围为空:0”。请看一下我的代码,让我知道如何解决这个问题。提前致谢

从主屏幕的这一行生成错误。

 title: Text( snapshot.data[index].datalist[index].title 

我的home文件如下:

    body: Container(

        child: Column(

          children: [
///////// Future Builder checks the API service getusers() future method every refreshed time
            Expanded(child: FutureBuilder(
              future: apiService.getCars(),
              builder: (context , snapshot){
                if(snapshot.hasData)
                {
                  return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (context, index){

                        ////// User List item button

                        return GestureDetector(
                          onTap: (){
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) => CarDetails(
                                car: snapshot.data[index].datalist[index].title,

                              )),
                            );

                          },
                          child:
                          Container(
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(10),
                              boxShadow: [
                                BoxShadow( color: Colors.grey.withOpacity(0.3),
                                  spreadRadius: 5,
                                  blurRadius: 7,
                                  offset: Offset(0, 5),
                                )
                              ],
                            ),
                            margin: EdgeInsets.symmetric(horizontal: 10 , vertical: 10),
                            padding: EdgeInsets.symmetric(horizontal: 10 , vertical: 10),
                            child: ListTile(
                              title: Text( snapshot.data[index].datalist[index].title  , style: TextStyle(
                                  fontSize: 18,color: Colors.black
                              ),),
                              subtitle: Text( 'car Name', style: TextStyle(
                                  fontSize: 18,color: Colors.black
                              ),),
                 
            
                            ),
                          ),
                        );
                      });
                }else{
                  //////// Loading Circle from Spinkit Plugin
                  return Container(
                    child: Center(
                      child: SpinKitCircle(
                        color: Colors.orange,
                      ),
                    ),
                  );
                }
              },
            ))

          ],
        ) ,
      ),

这是我的豆类(car.dart)

 import 'dart:convert';

Car carFromJson(String str) => Car.fromJson(json.decode(str));

String carToJson(Car data) => json.encode(data.toJson());

class Car {
  Car({
    this.status,
    this.data,
  });

  int status;
  List<Datum> data;

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

  Map<String, dynamic> toJson() => {
    "status": status,
    "data": List<dynamic>.from(data.map((x) => x.toJson())),
  };
}

class Datum {
  Datum({
    this.id,
    this.title,
    this.description,
    this.address,
    this.postcode,
    this.phoneNumber,
    this.latitude,
    this.longitude,
    this.image,
  });

  int id;
  String title;
  String description;
  String address;
  String postcode;
  String phoneNumber;
  String latitude;
  String longitude;
  Image image;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
    id: json["id"],
    title: json["title"],
    description: json["description"],
    address: json["address"],
    postcode: json["postcode"],
    phoneNumber: json["phoneNumber"],
    latitude: json["latitude"],
    longitude: json["longitude"],
    image: Image.fromJson(json["image"]),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "title": title,
    "description": description,
    "address": address,
    "postcode": postcode,
    "phoneNumber": phoneNumber,
    "latitude": latitude,
    "longitude": longitude,
    "image": image.toJson(),
  };
}

class Image {
  Image({
    this.small,
    this.medium,
    this.large,
  });

  String small;
  String medium;
  String large;

  factory Image.fromJson(Map<String, dynamic> json) => Image(
    small: json["small"],
    medium: json["medium"],
    large: json["large"],
  );

  Map<String, dynamic> toJson() => {
    "small": small,
    "medium": medium,
    "large": large,
  };
}

这是我的 get cars 方法和 JSON 响应正文

Future<List<Car>> getCars() async {
    final response = await http.get(Uri.parse(apiUrl));

    ///// checking the status code is successful
    if (response.statusCode == 200) {
     
      return getCarList(response.body);
    } else {
      throw Exception('Unable to fetch data from API');
    }
  }

 List<Car> getCarList(String responseBody) {
    final parsed = json.decode(responseBody);
    final List<dynamic> cars= parsed["data"];
    return (cars.map((json) => Car.fromJson(json)).toList());
  }

【问题讨论】:

  • 能否展示一下 getCars() 方法和 Json 响应体。

标签: json list flutter


【解决方案1】:

没有称为datalist的字段,因此更改错误导致如下行。

 title: Text( snapshot.data[index].data[index].title 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    相关资源
    最近更新 更多