skip to Main Content

This is my code

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:macistan/Standing.dart';

class InformationPage extends StatelessWidget {
  const InformationPage({Key? key}) : super(key: key);

  Future<List<StandingElement>> getstanding() async {
    try {
      var response = await Dio().get(
        "https://v3.football.api-sports.io/standings?league=203&season=2023",
        options: Options(headers: {
          'x-rapidapi-host': "v3.football.api-sports.io",
          'x-rapidapi-key': "7e75a8fd4dbc1400b449c8d5f8051cb0",
        }),
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.toString());

        final standings = Standing.fromJson(data);

        return standings.response[0].standings; // Assuming you want the standings list.
      }
      return [];
    } catch (e) {
      debugPrint(e.toString());
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 6,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.black,
        ),
        body: Container(
          child: Column(
            children: [
              Container(
                child: Text("hdslgfagwsıwplerguwgeŞIUwepıuy"),
              ),
              Container(),
              Container(
                height: 50,
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.zero,
                  color: Colors.black,
                ),
                child: const TabBar(
                  unselectedLabelColor: Colors.blue,
                  labelColor: Colors.white,
                  isScrollable: true,
                  indicator: BoxDecoration(
                    borderRadius: BorderRadius.only(),
                    color: Colors.blue,
                  ),
                  tabs: [
                    Tab(child: Text("Puan Durumu")),
                    Tab(child: Text("Form")),
                    Tab(child: Text("Fikstür")),
                    Tab(child: Text("İstatistik")),
                    Tab(child: Text("Transferler")),
                    Tab(child: Text("Haber")),
                  ],
                ),
              ),
              Expanded(
                child: TabBarView(
                  children: [
                    // Puan Durumu Tabı
                    Container(
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Container(
                                padding: EdgeInsets.all(5),
                                alignment: Alignment.center,
                                width: 10,
                                height: 30,
                                child: Text('#'),
                              ),
                              SizedBox(width: 15),
                              Container(
                                width: 120,
                                alignment: Alignment.center,
                                child: Text('#Takım'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('O'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('G'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('B'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('M'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('A'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('Y'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('AV'),
                              ),
                              SizedBox(width: 10),
                              Container(
                                alignment: Alignment.center,
                                width: 20,
                                child: Text('P'),
                              ),
                            ],
                          ),
                          Expanded(
                            child: FutureBuilder<List<StandingElement>>(
                              future: getstanding(),
                              builder: (context, snapshot) {
                                if (snapshot.connectionState ==
                                    ConnectionState.waiting) {
                                  return CircularProgressIndicator();
                                } else if (snapshot.hasError) {
                                  return Text("Error: ${snapshot.error}");
                                } else if (!snapshot.hasData ||
                                    snapshot.data!.isEmpty) {
                                  return Text("No data available");
                                } else {
                                  return ListView.builder(
                                    itemCount: snapshot.data?.length,
                                    itemBuilder: (context, index) {
                                      final standing =
                                      snapshot.data![index];
                                      return _buildTeamRow(
                                        standing.rank,
                                        standing.team.name,
                                        standing.points,
                                        standing.goalsDiff,
                                        standing.all.played,
                                        standing.all.win,
                                        standing.all.draw,
                                        standing.all.lose,
                                        standing.all.goals.goalsFor,
                                        standing.all.goals.against,
                                      );
                                    },
                                  );
                                }
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(color: Colors.white), // Form Tabı
                    Container(color: Colors.purple), // Fikstür Tabı
                    Container(color: Colors.red), // İstatistik Tabı
                    Container(color: Colors.blue), // Transferler Tabı
                    Container(color: Colors.green), // Haber Tabı
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTeamRow(
      int Sira,
      String teamName,
      int O,
      int G,
      int B,
      int M,
      int A,
      int Y,
      int AV,
      int P) {
    return Container(
      color: Colors.grey,
      child: Row(
        children: [
          Container(
            color: Colors.grey,
            child: Text("$Sira"),
            padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
            alignment: Alignment.center,
            width: 10,
            height: 30,
          ),
          SizedBox(width: 15),
          Container(
            color: Colors.grey,
            child: Text("$teamName"),
            width: 120,
            alignment: Alignment.center,
          ),
          SizedBox(width: 10),
          Container(
            color: Colors.grey,
            child: Text("$O"),
            alignment: Alignment.center,
            width: 20,
          ),
          SizedBox(width: 10),
          Container(
            color: Colors.grey,
            child: Text("$G"),
            alignment: Alignment.center,
            width: 20,
          ),
          SizedBox(width: 10),
          Container(
            color: Colors.grey,
            child: Text("$B"),
            alignment: Alignment.center,
            width: 20,
          ),
          SizedBox(width: 10),
          Container(
            color: Colors.grey,
            child: Text("$M"),
            alignment: Alignment.center,
            width: 20,
          ),
          SizedBox(width: 10),
          Container(
            color: Colors.grey,
            child: Text("$A"),
            alignment: Alignment.center,
            width: 20,
          ),
          SizedBox(width: 10),
          Container(
            color: Colors.grey,
            child: Text("$Y"),
            alignment: Alignment.center,
            width: 20,
          ),
          SizedBox(width: 10),
          Container(
            color: Colors.grey,
            child: Text("$AV"),
            alignment: Alignment.center,
            width: 20,
          ),
          SizedBox(width: 15),
          Container(
            color: Colors.grey,
            child: Text("$P"),
          ),
        ],
      ),
    );
  }
}

This is my class

import 'package:meta/meta.dart';
import 'dart:convert';

class Standing {
  final String standingGet;
  final Parameters parameters;
  final List<dynamic> errors;
  final int results;
  final Paging paging;
  final List<Response> response;

  Standing({
    required this.standingGet,
    required this.parameters,
    required this.errors,
    required this.results,
    required this.paging,
    required this.response,
  });

  factory Standing.fromRawJson(String str) => Standing.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Standing.fromJson(Map<String, dynamic> json) => Standing(
    standingGet: json["get"],
    parameters: Parameters.fromJson(json["parameters"]),
    errors: List<dynamic>.from(json["errors"].map((x) => x)),
    results: json["results"],
    paging: Paging.fromJson(json["paging"]),
    response: List<Response>.from(json["response"].map((x) => Response.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "get": standingGet,
    "parameters": parameters.toJson(),
    "errors": List<dynamic>.from(errors.map((x) => x)),
    "results": results,
    "paging": paging.toJson(),
    "response": List<dynamic>.from(response.map((x) => x.toJson())),
  };

}

class Paging {
  final int current;
  final int total;

  Paging({
    required this.current,
    required this.total,
  });

  factory Paging.fromRawJson(String str) => Paging.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Paging.fromJson(Map<String, dynamic> json) => Paging(
    current: json["current"],
    total: json["total"],
  );

  Map<String, dynamic> toJson() => {
    "current": current,
    "total": total,
  };
}

class Parameters {
  final String league;
  final String season;

  Parameters({
    required this.league,
    required this.season,
  });

  factory Parameters.fromRawJson(String str) => Parameters.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Parameters.fromJson(Map<String, dynamic> json) => Parameters(
    league: json["league"],
    season: json["season"],
  );

  Map<String, dynamic> toJson() => {
    "league": league,
    "season": season,
  };
}

class Response {
  final League league;
  final List<StandingElement> standings;

  Response({
    required this.league,
    required this.standings,
  });

  factory Response.fromRawJson(String str) => Response.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Response.fromJson(Map<String, dynamic> json) => Response(
    league: League.fromJson(json["league"]),
    standings: List<StandingElement>.from(json["standings"].map((x) => StandingElement.fromJson(x))),
  );

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

class League {
  final int id;
  final Name name;
  final String country;
  final String logo;
  final String flag;
  final int season;

  League({
    required this.id,
    required this.name,
    required this.country,
    required this.logo,
    required this.flag,
    required this.season,
  });

  factory League.fromRawJson(String str) => League.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory League.fromJson(Map<String, dynamic> json) => League(
    id: json["id"],
    name: nameValues.map[json["name"]]!,
    country: json["country"],
    logo: json["logo"],
    flag: json["flag"],
    season: json["season"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": nameValues.reverse[name],
    "country": country,
    "logo": logo,
    "flag": flag,
    "season": season,
  };
}

enum Name {
  SPER_LIG
}

final nameValues = EnumValues({
  "Süper Lig": Name.SPER_LIG
});

class StandingElement {
  final int rank;
  final Team team;
  final int points;
  final int goalsDiff;
  final Name group;
  final String form;
  final Status status;
  final String description;
  final All all;
  final All home;
  final All away;
  final DateTime update;

  StandingElement({
    required this.rank,
    required this.team,
    required this.points,
    required this.goalsDiff,
    required this.group,
    required this.form,
    required this.status,
    required this.description,
    required this.all,
    required this.home,
    required this.away,
    required this.update,
  });

  factory StandingElement.fromRawJson(String str) => StandingElement.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory StandingElement.fromJson(Map<String, dynamic> json) => StandingElement(
    rank: json["rank"],
    team: Team.fromJson(json["team"]),
    points: json["points"],
    goalsDiff: json["goalsDiff"],
    group: nameValues.map[json["group"]]!,
    form: json["form"],
    status: statusValues.map[json["status"]]!,
    description: json["description"],
    all: All.fromJson(json["all"]),
    home: All.fromJson(json["home"]),
    away: All.fromJson(json["away"]),
    update: DateTime.parse(json["update"]),
  );

  Map<String, dynamic> toJson() => {
    "rank": rank,
    "team": team.toJson(),
    "points": points,
    "goalsDiff": goalsDiff,
    "group": nameValues.reverse[group],
    "form": form,
    "status": statusValues.reverse[status],
    "description": description,
    "all": all.toJson(),
    "home": home.toJson(),
    "away": away.toJson(),
    "update": update.toIso8601String(),
  };
}

class All {
  final int played;
  final int win;
  final int draw;
  final int lose;
  final Goals goals;

  All({
    required this.played,
    required this.win,
    required this.draw,
    required this.lose,
    required this.goals,
  });

  factory All.fromRawJson(String str) => All.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory All.fromJson(Map<String, dynamic> json) => All(
    played: json["played"],
    win: json["win"],
    draw: json["draw"],
    lose: json["lose"],
    goals: Goals.fromJson(json["goals"]),
  );

  Map<String, dynamic> toJson() => {
    "played": played,
    "win": win,
    "draw": draw,
    "lose": lose,
    "goals": goals.toJson(),
  };
}

class Goals {
  final int goalsFor;
  final int against;

  Goals({
    required this.goalsFor,
    required this.against,
  });

  factory Goals.fromRawJson(String str) => Goals.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory Goals.fromJson(Map<String, dynamic> json) => Goals(
    goalsFor: json["for"],
    against: json["against"],
  );

  Map<String, dynamic> toJson() => {
    "for": goalsFor,
    "against": against,
  };
}

enum Status {
  SAME
}

final statusValues = EnumValues({
  "same": Status.SAME
});

class Team {
  final int id;
  final String name;
  final String logo;

  Team({
    required this.id,
    required this.name,
    required this.logo,
  });

  factory Team.fromRawJson(String str) => Team.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

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

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "logo": logo,
  };
}

class EnumValues<T> {
  Map<String, T> map;
  late Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    reverseMap = map.map((k, v) => MapEntry(v, k));
    return reverseMap;
  }
}

I get this error

I/flutter (10969): FormatException: Unexpected character (at character 2)
I/flutter (10969): {get: standings, parameters: {league: 203, season: 2023}, errors: [], resul…
I/flutter (10969): ^
I/flutter (10969):

How can I get this error?
I can’t find how to solve it.

I can write the response from the API to the screen, but I cannot decode it.

2

Answers


  1. Dio already decodes it and puts it in response.data, so you shouldn’t decode it yourself, and definitely not the response.toString().

    So replace

        final data = json.decode(response.toString());
    
        final standings = Standing.fromJson(data);
    

    with

        final standings = Standing.fromJson(response.data);
    

    EDIT:
    It also seems that you have errors in the structure of your data classes. Like you have that Response has a league and a standings but standings really is not a part of that in the api and is actually a field of League. Make sure you have it according to the api result.

    Login or Signup to reply.
  2.   if (response.statusCode == 200) {
          final standings = (json.decode(jsonEncode(response.data)) as List)
              .map((i) => Standing.fromJson(i))
              .toList();
    
          return right(standings);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search