0

I' trying to parse this type of json :

    "teams": [
        {
            "id": 1,
            "name": "New Jersey Devils",
            "link": "/api/v1/teams/1",
            "venue": {
                "name": "Prudential Center",
                "link": "/api/v1/venues/null",
                "city": "Newark",
                "timeZone": {
                    "id": "America/New_York",
                    "offset": -4,
                    "tz": "EDT"
                }
            },
            "abbreviation": "NJD",
            "teamName": "Devils",
            "locationName": "New Jersey",
            "firstYearOfPlay": "1982",
            "division": {
                "id": 18,
                "name": "Metropolitan",
                "nameShort": "Metro",
                "link": "/api/v1/divisions/18",
                "abbreviation": "M"
            }.........

But I only want the 'id' and 'name' attribute.
Here's my model :

class TeamDetail{
  final int id;
  final String name;

  TeamDetail({this.id, this.name});

  factory TeamDetail.fromJson(Map<String, dynamic> json){
    return TeamDetail(
      id: json["id"],
      name: json["name"],
    );
  }
}

And my method:

Future<TeamDetail> getTeamDetail() async{
  final response = await http.get('https://statsapi.web.nhl.com/api/v1/teams/1');

  if(response.statusCode == 200){

    return TeamDetail.fromJson(json.decode(response.body));

  }else{
    throw Exception("Failed to load");
  }
}

But when I call the method, I always receive a null value. Can you help me please. Thank you

1 Answer 1

1

You can copy paste run full code blow
You can return List<TeamDetail>
code snippet

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
...
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        copyright: json["copyright"],
        teams: List<TeamDetail>.from(
            json["teams"].map((x) => TeamDetail.fromJson(x))),
      );

working demo

enter image description here

full code

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

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

class Payload {
  Payload({
    this.copyright,
    this.teams,
  });

  String copyright;
  List<TeamDetail> teams;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        copyright: json["copyright"],
        teams: List<TeamDetail>.from(
            json["teams"].map((x) => TeamDetail.fromJson(x))),
      );
}

class TeamDetail {
  TeamDetail({
    this.id,
    this.name,
  });

  int id;
  String name;

  factory TeamDetail.fromJson(Map<String, dynamic> json) => TeamDetail(
        id: json["id"],
        name: json["name"],
      );
}

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<List<TeamDetail>> _future;

  Future<List<TeamDetail>> getTeamDetail() async {
    final response =
        await http.get('https://statsapi.web.nhl.com/api/v1/teams/1');

    if (response.statusCode == 200) {
      var payload = payloadFromJson(response.body);
      return payload.teams;
    } else {
      throw Exception("Failed to load");
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<TeamDetail>> 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.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].id.toString()),
                                    Spacer(),
                                    Text(snapshot.data[index].name),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.