'Learning flutter from c# models and http call using http.dart for first time

I am learning dart coming from a c# back ground and flutter. I am following this tutorial https://www.djamware.com/post/5f308ef7185c336b811b362a/flutter-tutorial-consume-crud-rest-api-android-and-ios-apps and I don't no how up to date

import 'dart:html';

class Players {
  final int Id;
  final int Type;
  final String PlayerLevel;
  final String FirstName;
  final String Surname;

  Players(this.Id, this.Type, this.PlayerLevel, this.FirstName, this.Surname);

 factory Players.fromJson(Map<String, dynamic> json) {
   return Players(
   id: json['id'] as int,
   type: json['type'] as String,
   PlayerLevel: json['playerlevel'] as String,
   FirstName: json['firstname'] as String,
   Surname: json['surname'] as String,
 );

}
@override
String toString() {
  return 'Players{id: $Id, firstName: $FirstName, lastName: $Surname}';
}
}

Flutter http call

class ApiService {
  final String apiUrl = "https://api-hockeylab.com/api";
  final String getAllPlayersEndPoint = "/GetAllPlayers/";

  Future<List<Players>> getAllPlayers() async {
    final getallPlayersUrl = Uri.parse(apiUrl + getAllPlayersEndPoint);

    Response res = await get(getallPlayersUrl);
    if (res.statusCode == 200) {
      List<dynamic> body = jsonDecode(res.body);
      List<Players> players =
          body.map((dynamic item) => Players.fromJson(item)).toList();
      return players;
    } else {
      throw "Failed to load cases list";
    }
  }
}

Normally in c# I would do something as simple

public async Task<List<Players>> GetALLPlayers()
{
    List<Players> _result = new List<Players>();
    EnsureHttpClientCreated();
    var uri = new Uri(string.Format(Constants.BaseUrl + Constants.ApiSegmant + Constants.GetAllPlayers, string.Empty));
    await AddAuthenicationHeader();
    var response = await httpClient.GetAsync(uri);

        if (response.IsSuccessStatusCode)
        {
            var byteArray = await response.Content.ReadAsByteArrayAsync();

            var content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            _result = JsonConvert.DeserializeObject<List<Players>>(content);
        }
        
    return _result.ToList();

}

How in flutter do I pass in the default request headers as it passes my jwt authentication token but also my Players model is not compiling right in flutter what am I doing wrong in the above flutter code.

private void CreateHttpClient()
{
    _httpClientHandler = new HttpClientHandler
    {
        AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
    };

    httpClient = new HttpClient(_httpClientHandler, false)
    {
        Timeout = _timeout
    };

    httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(ClientUserAgent);

    if (!string.IsNullOrWhiteSpace(Constants.BaseUrl))
    {
        httpClient.BaseAddress = new Uri(Constants.BaseUrl);
    }

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));
}
private void EnsureHttpClientCreated()
{
    if (httpClient == null)
    {
        CreateHttpClient();
    }
}


Solution 1:[1]

Your factory constructor is trying to call the main constructor using named parameters, but it uses positional parameters. Updated class below (with Dart style tweaks).

class Player {
  final int id;
  final int type;
  final String playerLevel;
  final String firstName;
  final String surname;

  Player(this.id, this.type, this.playerLevel, this.firstName, this.surname);

  factory Player.fromJson(Map<String, dynamic> json) {
    return Player(
      json['id'],
      json['type'],
      json['playerlevel'],
      json['firstname'],
      json['surname'],
    );
  }

  @override
  String toString() =>
      'Players{id: $id, firstName: $firstName, lastName: $surname}';
}

To add headers, the get method takes a named parameter headers, so will become:

await get(url, headers: {'some-header': 'some_value'});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard Heap