0

I have try to receive a list of categories by the api, but I got this error! When I change my froomJson to fromJson(List) my variables dont accept a String value, because then expected a int value.

My CategoryModel

`

import 'dart:convert';

class Category {
  String? id;
  String? tenantId;
  String? userId;
  String? name;
  String? description;
  String? createdAt;
  String? updatedAt;

  Category(
      {this.id,
      this.tenantId,
      this.userId,
      this.name,
      this.description,
      this.createdAt,
      this.updatedAt});

  Category.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    tenantId = json['tenant_id'];
    userId = json['user_id'];
    name = json['name'];
    description = json['description'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = id;
    data['tenant_id'] = tenantId;
    data['user_id'] = userId;
    data['name'] = name;
    data['description'] = description;
    data['created_at'] = createdAt;
    data['updated_at'] = updatedAt;
    return data;
  }
}

`

My API Call

`

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mcea_master_application/config/config.dart';
import 'package:mcea_master_application/models/CategoryModel.dart';

final String urlCategories = '${Config.baseUrl}categories';

Future getMceaCategories() async {
  final response = await http.get(Uri.parse(urlCategories), headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer 6|b8Wi0V95n3fgZyCg3DiJFymdx10jZsX2K58vpVcq',
  });
  if (response.statusCode == 200) {
    var categories = Category.fromJson(jsonDecode(response.body));
    // return jsonDecode(response.body);
    return categories;
  } else {
    throw Exception('Falha ao carregar as categorias!');
  }
}

`

if return directly response.body without map my model, it works!

My Page

`

import 'dart:html';
import 'dart:js';

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:mcea_master_application/config/config.dart';
import 'package:mcea_master_application/config/mcea-api.dart';
import 'package:mcea_master_application/models/CategoryModel.dart';

// ignore: use_key_in_widget_constructors

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text(Config.title),
      ),
      body: FutureBuilder(
          future: getMceaCategories(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              print(snapshot.data);
              return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(snapshot.data[index]['name']),
                    );
                  });
            }
            if (snapshot.hasError) {
              print(snapshot.error);
            }
            return const Center(
              child: CircularProgressIndicator(),
            );
          }),
    );
  }
}

`

My Json

[
{
    "id": "6f8c3398-c671-424f-a31c-86c0589ab6a7",
    "tenant_id": "866a0842-e227-41b8-a73a-d224f6599412",
    "user_id": "e66beb23-50ee-46e3-b6c6-d146f7f3987f",
    "name": "Treinos para Perna",
    "description": "Aqui você tem todos os treinos para a perna",
    "created_at": "2022-12-14T22:11:06.000000Z",
    "updated_at": "2022-12-14T22:11:06.000000Z"
},
{
    "id": "a65553cd-4f17-4629-9ef9-648797e4d687",
    "tenant_id": "866a0842-e227-41b8-a73a-d224f6599412",
    "user_id": "e66beb23-50ee-46e3-b6c6-d146f7f3987f",
    "name": "Treinos para a Bunda",
    "description": "Aqui você encontra todos os treinos para a bunda",
    "created_at": "2022-12-14T22:11:21.000000Z",
    "updated_at": "2022-12-14T22:11:21.000000Z"
},
{
    "id": "c8f07e7c-7f25-4713-b4d2-f901a5bda8be",
    "tenant_id": "866a0842-e227-41b8-a73a-d224f6599412",
    "user_id": "e66beb23-50ee-46e3-b6c6-d146f7f3987f",
    "name": "Comece Aqui",
    "description": "Aqui você aprende a usar o nosso aplicativo",
    "created_at": "2022-12-12T23:21:22.000000Z",
    "updated_at": "2022-12-14T22:11:34.000000Z"
}

]

I tried this solutions, but nothing works for me!

My Sdk version

sdk: '>=2.18.5 <3.0.0'

1 Answers1

0

Seems like the api is returning a List in your code u have done this var categories = Category.fromJson(jsonDecode(response.body)); the response.body` will be an Array of categories, u might have to do something like this

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:mcea_master_application/config/config.dart';
import 'package:mcea_master_application/models/CategoryModel.dart';

final String urlCategories = '${Config.baseUrl}categories';

Future getMceaCategories() async {
  final response = await http.get(Uri.parse(urlCategories), headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer 6|b8Wi0V95n3fgZyCg3DiJFymdx10jZsX2K58vpVcq',
  });
  if (response.statusCode == 200) {
    final result = jsonDecode(response.body) as List<Map<String,dynamic>>;
    final categories = result.map((data) => Category.fromJson(data)).toList();

    return categories;
  } else {
    throw Exception('Falha ao carregar as categorias!');
  }
}

Afzal
  • 291
  • 3
  • 5