flutter Как извлечь предстоящие данные и объекты в silverlist и на экране заголовка

#flutter

#flutter

Вопрос:

{"response":{"status":true,"message":null,"data":{"upcoming_match":[{"is_lineup":0,"series_id":115991,"match_id":45643,"guru_url":"","series_name":"DD20","local_team_id":115885,"local_team_name":"WCC","local_team_flag":"http://sportsindia11.com//uploads/team_flag/wcc.png","visitor_team_id":115892,"visitor_team_name":"DDC","visitor_team_flag":"http://sportsindia11.com//uploads/team_flag/ddc.png","star_date":"2020-09-12T00:00:00","star_time":"07:00","total_contest":0,"server_time":"2020-09-11 22:52:32"},{"is_lineup":0,"series_id":115991,"match_id":45644,"guru_url":"","series_name":"DD20","local_team_id":115889,"local_team_name":"SD","local_team_flag":"http://sportsindia11.com//uploads/team_flag/sd.png","visitor_team_id":115890,"visitor_team_name":"PCC","visitor_team_flag":"http://sportsindia11.com//uploads/team_flag/pcc.png","star_date":"2020-09-12T00:00:00","star_time":"07:00","total_contest":7,"server_time":"2020-09-11 22:52:32"},{"is_lineup":0,"series_id":116363,"match_id":45579,"guru_url":"","series_name":"IWS50","local_team_id":116365,"local_team_name":"SW","local_team_flag":"http://sportsindia11.com//uploads/team_flag/sw.png","visitor_team_id":116366,"visitor_team_name":"TW","visitor_team_flag":"http://sportsindia11.com//uploads/team_flag/tw.png","star_date":"2020-09-13T00:00:00","star_time":"15:00","total_contest":0,"server_time":"2020-09-11 22:52:32"},{"is_lineup":0,"series_id":116531,"match_id":45501,"guru_url":"","series_name":"RHFT-2020","local_team_id":104877,"local_team_name":"VP","local_team_flag":"http://sportsindia11.com//uploads/team_flag/vp.png","visitor_team_id":104878,"visitor_team_name":"WS","visitor_team_flag":"http://sportsindia11.com//uploads/team_flag/ws.png","star_date":"2020-09-13T00:00:00","star_time":"15:00","total_contest":0,"server_time":"2020-09-11 22:52:32"}],"live_match":[],"completed_match":[],"version_code":1,"apk_url":"http://sportsindia11.com//sportsindia1101.apk"}}}

Ответ №1:

Посмотрите на этот созданный мной пример: это json, который вы предоставили:

 {
    "response": {
        "status": true,
        "message": null,
        "data": {
            "upcoming_match": [{
                "is_lineup": 0,
                "series_id": 115991,
                "match_id": 45643,
                "guru_url": "",
                "series_name": "DD20",
                "local_team_id": 115885,
                "local_team_name": "WCC",
                "local_team_flag": "http://sportsindia11.com//uploads/team_flag/wcc.png",
                "visitor_team_id": 115892,
                "visitor_team_name": "DDC",
                "visitor_team_flag": "http://sportsindia11.com//uploads/team_flag/ddc.png",
                "star_date": "2020-09-12T00:00:00",
                "star_time": "07:00",
                "total_contest": 0,
                "server_time": "2020-09-11 22:52:32"
            }, {
                "is_lineup": 0,
                "series_id": 115991,
                "match_id": 45644,
                "guru_url": "",
                "series_name": "DD20",
                "local_team_id": 115889,
                "local_team_name": "SD",
                "local_team_flag": "http://sportsindia11.com//uploads/team_flag/sd.png",
                "visitor_team_id": 115890,
                "visitor_team_name": "PCC",
                "visitor_team_flag": "http://sportsindia11.com//uploads/team_flag/pcc.png",
                "star_date": "2020-09-12T00:00:00",
                "star_time": "07:00",
                "total_contest": 7,
                "server_time": "2020-09-11 22:52:32"
            }, {
                "is_lineup": 0,
                "series_id": 116363,
                "match_id": 45579,
                "guru_url": "",
                "series_name": "IWS50",
                "local_team_id": 116365,
                "local_team_name": "SW",
                "local_team_flag": "http://sportsindia11.com//uploads/team_flag/sw.png",
                "visitor_team_id": 116366,
                "visitor_team_name": "TW",
                "visitor_team_flag": "http://sportsindia11.com//uploads/team_flag/tw.png",
                "star_date": "2020-09-13T00:00:00",
                "star_time": "15:00",
                "total_contest": 0,
                "server_time": "2020-09-11 22:52:32"
            }, {
                "is_lineup": 0,
                "series_id": 116531,
                "match_id": 45501,
                "guru_url": "",
                "series_name": "RHFT-2020",
                "local_team_id": 104877,
                "local_team_name": "VP",
                "local_team_flag": "http://sportsindia11.com//uploads/team_flag/vp.png",
                "visitor_team_id": 104878,
                "visitor_team_name": "WS",
                "visitor_team_flag": "http://sportsindia11.com//uploads/team_flag/ws.png",
                "star_date": "2020-09-13T00:00:00",
                "star_time": "15:00",
                "total_contest": 0,
                "server_time": "2020-09-11 22:52:32"
            }],
            "live_match": [],
            "completed_match": [],
            "version_code": 1,
            "apk_url": "http://sportsindia11.com//sportsindia1101.apk"
        }
    }
}
  

Это класс модели для этого:

 // To parse this JSON data, do
//
//     final events = eventsFromJson(jsonString);

import 'dart:convert';

Events eventsFromJson(String str) => Events.fromJson(json.decode(str));

String eventsToJson(Events data) => json.encode(data.toJson());

class Events {
    Events({
        this.response,
    });

    Response response;

    factory Events.fromJson(Map<String, dynamic> json) => Events(
        response: Response.fromJson(json["response"]),
    );

    Map<String, dynamic> toJson() => {
        "response": response.toJson(),
    };
}

class Response {
    Response({
        this.status,
        this.message,
        this.data,
    });

    bool status;
    dynamic message;
    Data data;

    factory Response.fromJson(Map<String, dynamic> json) => Response(
        status: json["status"],
        message: json["message"],
        data: Data.fromJson(json["data"]),
    );

    Map<String, dynamic> toJson() => {
        "status": status,
        "message": message,
        "data": data.toJson(),
    };
}

class Data {
    Data({
        this.upcomingMatch,
        this.liveMatch,
        this.completedMatch,
        this.versionCode,
        this.apkUrl,
    });

    List<UpcomingMatch> upcomingMatch;
    List<dynamic> liveMatch;
    List<dynamic> completedMatch;
    int versionCode;
    String apkUrl;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        upcomingMatch: List<UpcomingMatch>.from(json["upcoming_match"].map((x) => UpcomingMatch.fromJson(x))),
        liveMatch: List<dynamic>.from(json["live_match"].map((x) => x)),
        completedMatch: List<dynamic>.from(json["completed_match"].map((x) => x)),
        versionCode: json["version_code"],
        apkUrl: json["apk_url"],
    );

    Map<String, dynamic> toJson() => {
        "upcoming_match": List<dynamic>.from(upcomingMatch.map((x) => x.toJson())),
        "live_match": List<dynamic>.from(liveMatch.map((x) => x)),
        "completed_match": List<dynamic>.from(completedMatch.map((x) => x)),
        "version_code": versionCode,
        "apk_url": apkUrl,
    };
}

class UpcomingMatch {
    UpcomingMatch({
        this.isLineup,
        this.seriesId,
        this.matchId,
        this.guruUrl,
        this.seriesName,
        this.localTeamId,
        this.localTeamName,
        this.localTeamFlag,
        this.visitorTeamId,
        this.visitorTeamName,
        this.visitorTeamFlag,
        this.starDate,
        this.starTime,
        this.totalContest,
        this.serverTime,
    });

    int isLineup;
    int seriesId;
    int matchId;
    String guruUrl;
    String seriesName;
    int localTeamId;
    String localTeamName;
    String localTeamFlag;
    int visitorTeamId;
    String visitorTeamName;
    String visitorTeamFlag;
    DateTime starDate;
    String starTime;
    int totalContest;
    DateTime serverTime;

    factory UpcomingMatch.fromJson(Map<String, dynamic> json) => UpcomingMatch(
        isLineup: json["is_lineup"],
        seriesId: json["series_id"],
        matchId: json["match_id"],
        guruUrl: json["guru_url"],
        seriesName: json["series_name"],
        localTeamId: json["local_team_id"],
        localTeamName: json["local_team_name"],
        localTeamFlag: json["local_team_flag"],
        visitorTeamId: json["visitor_team_id"],
        visitorTeamName: json["visitor_team_name"],
        visitorTeamFlag: json["visitor_team_flag"],
        starDate: DateTime.parse(json["star_date"]),
        starTime: json["star_time"],
        totalContest: json["total_contest"],
        serverTime: DateTime.parse(json["server_time"]),
    );

    Map<String, dynamic> toJson() => {
        "is_lineup": isLineup,
        "series_id": seriesId,
        "match_id": matchId,
        "guru_url": guruUrl,
        "series_name": seriesName,
        "local_team_id": localTeamId,
        "local_team_name": localTeamName,
        "local_team_flag": localTeamFlag,
        "visitor_team_id": visitorTeamId,
        "visitor_team_name": visitorTeamName,
        "visitor_team_flag": visitorTeamFlag,
        "star_date": starDate.toIso8601String(),
        "star_time": starTime,
        "total_contest": totalContest,
        "server_time": serverTime.toIso8601String(),
    };
}

  

Это основной пользовательский интерфейс с sliverList:

 import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:json_parsing_example/models.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Login());
  }
}

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  List<UpcomingMatch> upcomingMatches = List();
  bool _isLoading = false;

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

  getData() async {
    setState(() {
      _isLoading = true;
    });
    String data =
        await DefaultAssetBundle.of(context).loadString("json/parse.json");
    print('This is the sttring : $data');
// I have taken the local String you just have to call you http request above.
// var response =  await http.get('your url ') or same for http.post()
//when you get the response the  and the pass to the below model.
// see the following example .
//  final res = eventsFromJson(response.body);
    // Comment this below when making the http call.
    final res = eventsFromJson(data);
    print('This is the data: ${json.encode(res)}');
    upcomingMatches = res.response.data.upcomingMatch;
    setState(() {
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
      child: _isLoading
          ? CircularProgressIndicator()
          : CustomScrollView(slivers: [
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    return Container(
                      child: Card(
                        child: Column(
                          children: <Widget>[
                            Text('This is seriesname: ${upcomingMatches[index].seriesName}'),
                            Text('This is series id :${upcomingMatches[index].seriesId}'),
                          ],
                        ),
                      ),
                    );
                  },
                  childCount: upcomingMatches.length,
                ),
              ),
            ]),
    ));
  }
}

  

Проверьте и дайте мне знать, работает ли это.

Комментарии:

1. здравствуйте, Сагар, пожалуйста, проверьте ваш метод getdata, в котором я хочу получать данные через restapi, поэтому, пожалуйста, проверьте это. спасибо за предварительную помощь

2. Когда вы вызываете API в ответе. тело, которое является строкой, которую вы получаете, вам просто нужно передать ее в конечный res = eventsFromJson(response.body); в остальном все то же самое.

3. Проверьте это и дайте мне знать, если вы застряли в какой-либо момент.