如何访问flutter中的json列表?

问题描述 投票:0回答:1

我试图访问一个通过API发送的儿子。但JSON中包含一个列表,我无法访问它。我无法访问它,请帮助我。

这是我从API接收的JSON。

{
  "message": "success",
  "events": [
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6acc6836b3263e4f50662",
      "eventid": "01",
      "schoolname": "abc school",
      "teacherid": "0015",
      "teachername": "Malar",
      "eventdate": "2000-03-05T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6ad38836b3263e4f50665",
      "eventid": "02",
      "schoolname": "abc school",
      "teacherid": "0016",
      "teachername": "Malaring",
      "eventdate": "2000-06-02T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
  ]
}

我的PODO类是

// To parse this JSON data, do
//
//     final allEvents = allEventsFromJson(jsonString);

import 'dart:convert';

GetAllEvents allEventsFromJson(String str) => GetAllEvents.fromJson(json.decode(str));

String allEventsToJson(GetAllEvents data) => json.encode(data.toJson());

class GetAllEvents {
  GetAllEvents({
    this.message,
    this.events,
  });

  String message;
  List<Event> events;

  factory GetAllEvents.fromJson(Map<String, dynamic> json) => GetAllEvents(
    message: json["message"],
    events: List<Event>.from(json["events"].map((x) => Event.fromJson(x))),
  );

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

class Event {
  Event({
    this.schools,
    this.participants,
    this.id,
    this.eventid,
    this.schoolname,
    this.teacherid,
    this.teachername,
    this.eventdate,
    this.eventname,
    this.eventdescription,
    this.eventtype,
    this.eventimage,
    this.v,
  });

  int schools;
  int participants;
  String id;
  String eventid;
  String schoolname;
  String teacherid;
  String teachername;
  DateTime eventdate;
  String eventname;
  String eventdescription;
  String eventtype;
  String eventimage;
  int v;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
    schools: json["schools"],
    participants: json["participants"],
    id: json["_id"],
    eventid: json["eventid"],
    schoolname: json["schoolname"],
    teacherid: json["teacherid"],
    teachername: json["teachername"],
    eventdate: DateTime.parse(json["eventdate"]),
    eventname: json["eventname"],
    eventdescription: json["eventdescription"],
    eventtype: json["eventtype"],
    eventimage: json["eventimage"],
    v: json["__v"],
  );

  Map<String, dynamic> toJson() => {
    "schools": schools,
    "participants": participants,
    "_id": id,
    "eventid": eventid,
    "schoolname": schoolname,
    "teacherid": teacherid,
    "teachername": teachername,
    "eventdate": eventdate.toIso8601String(),
    "eventname": eventname,
    "eventdescription": eventdescription,
    "eventtype": eventtype,
    "eventimage": eventimage,
    "__v": v,
  };
}

而我的未来功能是:

final String getAllEventsUrl = "http://192.168.1.5:8080/api/events/getall";


  Future getAllEvents() async {
    Response response = await post(getAllEventsUrl);
    var result = response.body;
    var body = jsonDecode(result);
    return GetAllEvents.fromJson(body);
  }

而我的代码是:

Container(
      margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
      child: FutureBuilder(
        future: eventsApi.getAllEvents(),
        builder: (context, snapshot) {
          if(snapshot.hasData){
            print(snapshot.data);
            List<GetAllEvents> events = snapshot.data;
            ListView(
              children: events.map((e) => ListTile(title: Text(e.events[0].eventdescription),)).toList(),
            );
          }
          return Center(child: CircularProgressIndicator());
        },
      ),
    );

我得到这个错误

类型'GetAllEvents'不是类型'List'的子类型,我现在应该怎么做。请帮助我。

android ios google-chrome flutter flutter-layout
1个回答
1
投票

你可以复制粘贴运行完整的代码如下 步骤1:你可以提供类型 GetAllEventsFutureAsyncSnapshot<GetAllEvents> 第二步:你需要检查 connectionState

Future<GetAllEvents> _future;
...
@override
void initState() {
_future = getAllEvents();
...
Future<GetAllEvents> getAllEvents() async {
...
FutureBuilder(
        future: _future,
        builder: (context, AsyncSnapshot<GetAllEvents> snapshot) {
          switch (snapshot.connectionState) {
            ...
            case ConnectionState.waiting:
              return Center(child: CircularProgressIndicator());
            case ConnectionState.active:
              return Text('');
            case ConnectionState.done:
              if (snapshot.hasError) {
                ...
              } else {
                return ListView.builder(
                    itemCount: snapshot.data.events.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                          title: Text(snapshot
                              .data.events[index].eventdescription))

工作示范

enter image description here

全码

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

GetAllEvents allEventsFromJson(String str) =>
    GetAllEvents.fromJson(json.decode(str));

String allEventsToJson(GetAllEvents data) => json.encode(data.toJson());

class GetAllEvents {
  GetAllEvents({
    this.message,
    this.events,
  });

  String message;
  List<Event> events;

  factory GetAllEvents.fromJson(Map<String, dynamic> json) => GetAllEvents(
        message: json["message"],
        events: List<Event>.from(json["events"].map((x) => Event.fromJson(x))),
      );

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

class Event {
  Event({
    this.schools,
    this.participants,
    this.id,
    this.eventid,
    this.schoolname,
    this.teacherid,
    this.teachername,
    this.eventdate,
    this.eventname,
    this.eventdescription,
    this.eventtype,
    this.eventimage,
    this.v,
  });

  int schools;
  int participants;
  String id;
  String eventid;
  String schoolname;
  String teacherid;
  String teachername;
  DateTime eventdate;
  String eventname;
  String eventdescription;
  String eventtype;
  String eventimage;
  int v;

  factory Event.fromJson(Map<String, dynamic> json) => Event(
        schools: json["schools"],
        participants: json["participants"],
        id: json["_id"],
        eventid: json["eventid"],
        schoolname: json["schoolname"],
        teacherid: json["teacherid"],
        teachername: json["teachername"],
        eventdate: DateTime.parse(json["eventdate"]),
        eventname: json["eventname"],
        eventdescription: json["eventdescription"],
        eventtype: json["eventtype"],
        eventimage: json["eventimage"],
        v: json["__v"],
      );

  Map<String, dynamic> toJson() => {
        "schools": schools,
        "participants": participants,
        "_id": id,
        "eventid": eventid,
        "schoolname": schoolname,
        "teacherid": teacherid,
        "teachername": teachername,
        "eventdate": eventdate.toIso8601String(),
        "eventname": eventname,
        "eventdescription": eventdescription,
        "eventtype": eventtype,
        "eventimage": eventimage,
        "__v": v,
      };
}

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: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<GetAllEvents> _future;

  Future<GetAllEvents> getAllEvents() async {
    String jsonString = '''
    {
  "message": "success",
  "events": [
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6acc6836b3263e4f50662",
      "eventid": "01",
      "schoolname": "abc school",
      "teacherid": "0015",
      "teachername": "Malar",
      "eventdate": "2000-03-05T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    },
    {
      "schools": 0,
      "participants": 0,
      "_id": "5ed6ad38836b3263e4f50665",
      "eventid": "02",
      "schoolname": "abc school",
      "teacherid": "0016",
      "teachername": "Malaring",
      "eventdate": "2000-06-02T18:30:00.000Z",
      "eventname": "Science Workshop",
      "eventdescription": "This is a very grand event.",
      "eventtype": "science",
      "eventimage": "none",
      "__v": 0
    }
  ]
}
    ''';
    //Response response = await post(getAllEventsUrl);
    http.Response response = http.Response(jsonString, 200);
    var result = response.body;
    var body = jsonDecode(result);
    return GetAllEvents.fromJson(body);
  }

  @override
  void initState() {
    _future = getAllEvents();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<GetAllEvents> 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(
                        itemCount: snapshot.data.events.length,
                        itemBuilder: (context, index) {
                          return ListTile(
                              title: Text(snapshot
                                  .data.events[index].eventdescription));
                        });
                  }
              }
            }));
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.