-1

I need to fetch Category Data from my custom made API. I create a model, controller for fetch data from API with help of getx, but it give me error. I don't know what is the problem. Can anybody help me out please?

Here is my Category_slider.dart file as a view

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:get/get.dart';
import 'package:we_serve/controllers/CategoryController.dart';

import '../models/Category.dart';

class CategorySlider extends StatelessWidget {
  CategoryController categoryController = Get.put(CategoryController());
  
  // categoryController.
  @override
  Widget build(BuildContext context) {
    print(categoryController);
    return ListView.builder(
      scrollDirection: Axis.horizontal,
      shrinkWrap: true,
      padding: const EdgeInsets.only(
        right: 8,
      ),
      // itemCount: categoryController.,
      itemBuilder: (BuildContext context, int index) {
        return Container(
          child: Center(
            child: Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Container(
                    width: 200,
                    height: 120,

                    // width: double.infinity,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20),
                              side: BorderSide(color: Color(0xFF1818B4)))),
                      onPressed: () {},
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          // Text(
                          //   categoryController.category?.data![index].categoryName,
                          //   style: TextStyle(
                          //     color: Colors.black,
                          //   ),
                          // ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

Here is my Category.dart model file

class Category {
  List<Data>? data;

  Category({required this.data});

  Category.fromJson(Map<String, dynamic> json) {
    if (json['data'] != null) {
      data = <Data>[];
      json['data'].forEach((v) {
        data!.add(new Data.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.data != null) {
      data['data'] = this.data!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Data {
  int? id;
  String? image;
  String? categoryName;
  String? categoryDes;
  int? activation;
  String? createdAt;
  String? updatedAt;

  Data(
      {required this.id,
      required this.image,
      required this.categoryName,
      required this.categoryDes,
      required this.activation,
      required this.createdAt,
      required this.updatedAt});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    image = json['image'];
    categoryName = json['category_name'];
    categoryDes = json['category_des'];
    activation = json['activation'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['image'] = this.image;
    data['category_name'] = this.categoryName;
    data['category_des'] = this.categoryDes;
    data['activation'] = this.activation;
    data['created_at'] = this.createdAt;
    data['updated_at'] = this.updatedAt;
    return data;
  }
}

Here is my Controller CategoryController.dart file

import 'dart:convert';

import 'package:get/get.dart';
import 'package:we_serve/models/Category.dart';
import 'package:http/http.dart' as http;

class CategoryController extends GetxController{
  var isLoading = false.obs;
  Category? _category;

  // Category? get category => _category;

  fetchData() async {
    try{
      isLoading(true);
      http.Response response = await http.get(Uri.tryParse('http://127.0.0.1:8000/api/category')!);
      // print(response.statusCode);
      if(response.statusCode == 200){
        var result = jsonDecode(response.body);
        // print(result);
        _category = Category.fromJson(result);
      }else{
        print("Error Fetching data");
      }
    }catch(e){
      print("Error while getting data is $e");
    }finally{
      isLoading(false);
    }
  }


}

http://127.0.0.1:8000/api/category returning this json file

{
    "data": [
        {
            "id": 1,
            "image": "public/category_images/U5WWF8C0Pfz3dF44ejs7XkguuNoynsgYKO3CjpxY.jpg",
            "category_name": "test 1",
            "category_des": "test category 1",
            "activation": 1,
            "created_at": "2023-07-19T09:58:32.000000Z",
            "updated_at": "2023-07-19T09:58:32.000000Z"
        },
        {
            "id": 2,
            "image": "public/category_images/MBMi7FgEo1wlEDR4QbZRdRv6T6xWLUL2yddoMcg6.jpg",
            "category_name": "test 2",
            "category_des": "test category 2",
            "activation": 1,
            "created_at": "2023-07-19T09:58:53.000000Z",
            "updated_at": "2023-07-19T09:58:53.000000Z"
        },
        {
            "id": 3,
            "image": "public/category_images/oN8UZu9v6B504IfFbvPeSWEI3IvWGR8Rc1R5t1WP.jpg",
            "category_name": "test 3",
            "category_des": "test category 3",
            "activation": 1,
            "created_at": "2023-07-19T09:59:04.000000Z",
            "updated_at": "2023-07-19T10:10:03.000000Z"
        }
    ]
}

I don't know how to solve this, but it seems that in controller _category = Category.fromJson(result); this line of code doesn't work or doesn't store the data into _category list. I am not sure but just assuming there is some problem in model or controller.

1 Answers1

0

Try this as model

import 'dart:convert';

Category categoryFromJson(String str) => Category.fromJson(json.decode(str));

String categoryToJson(Category data) => json.encode(data.toJson());

class Category {
    List<Datum>? data;

    Category({
        this.data,
    });

    factory Category.fromJson(Map<String, dynamic> json) => Category(
        data: json["data"] == null ? [] : List<Datum>.from(json["data"]!.map((x) => Datum.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "data": data == null ? [] : List<dynamic>.from(data!.map((x) => x.toJson())),
    };
}

class Datum {
    int? id;
    String? image;
    String? categoryName;
    String? categoryDes;
    int? activation;
    DateTime? createdAt;
    DateTime? updatedAt;

    Datum({
        this.id,
        this.image,
        this.categoryName,
        this.categoryDes,
        this.activation,
        this.createdAt,
        this.updatedAt,
    });

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        image: json["image"],
        categoryName: json["category_name"],
        categoryDes: json["category_des"],
        activation: json["activation"],
        createdAt: json["created_at"] == null ? null : DateTime.parse(json["created_at"]),
        updatedAt: json["updated_at"] == null ? null : DateTime.parse(json["updated_at"]),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "image": image,
        "category_name": categoryName,
        "category_des": categoryDes,
        "activation": activation,
        "created_at": createdAt?.toIso8601String(),
        "updated_at": updatedAt?.toIso8601String(),
    };
}

then for the controller inside try putting this

class CategoryController extends GetxController{
  var isLoading = false.obs;
  Rx<Category> _category = Category().obs;

  // Category? get category => _category;

  fetchData() async {
    try{
      isLoading(true);
      http.Response response = await http.get(Uri.tryParse('http://127.0.0.1:8000/api/category')!);
      // print(response.statusCode);
      if(response.statusCode == 200){
        var result = jsonDecode(response.body);
        // print(result);
        _category.value = Category.fromJson(result);
       // try to add update()
        update();
      }else{
        print("Error Fetching data");
      }
    }catch(e){
      print("Error while getting data is $e");
    }finally{
      isLoading(false);
    }
  }


}

I hope this helps i think try to change the model for now

Update:

try wrp the code like this

This is for GetBuilder
// This particular builder is good for heavy widgets
// and for the state to change is need to add update();
// e.g.
// variable.value = "change";
// update(); // Require to add update below.
// for every states variables. 
   return GetBuilder<CategoryController>(
     init: CategoryController(),
     builder:(controller){
        return WidgetSome();
      }
    );

The other one is OBX

  // This on is good for light states changes in ui unlike getbuilder
  // as sample variable is like this
  // variable("change");
  // But i usually use GetBuilder but still depends on you.
  return Obx(
    ()=> 
      WidgetSome(),
  );

for http to add headers is simple it's already indicate on the package you used although need to type them like this,

final header = {
       'Content-type': 'application/json',
       'Accept': 'application/json'
     };
  final urlParse = Uri.parse(http://127.0.0.1:8000/api/category');
   http.Response response = await http.get(urlParse,headers: header);
Arbiter Chil
  • 1,061
  • 1
  • 6
  • 9