I want to show all categories but it shows me only loading and it keeps loading

692 Views Asked by At

I am bulding an e-commerce app so i want to connect with my site https://gngbd.com

so i am giving my all codes below.

here is my config.dart

class Config {
  static String key = "";
  static String secret = "";
  static String url = "https://gngbd.com/wp-json/wc/v3";
  static String customerUrl = "";
  static String tokenUrl = "";
  static String categoriesUrl = "products/categories";
}

Here is my Category.dart

import 'package:flutter/material.dart';
import 'package:gng_app/api_service.dart';
import 'package:gng_app/models/categories.dart';
import 'package:image/image.dart' as Image;

class Category extends StatefulWidget {
  @override
  _CategoryState createState() => _CategoryState();
}

class _CategoryState extends State<Category> {
  APIService apiService;

  void initStat() {
    apiService = new APIService();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(left: 16, top: 4),
                child: Text(
                  "All Categories",
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 16, top: 4, right: 10),
                child: Text(
                  "View All",
                  style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: Colors.red),
                ),
              ),
            ],
          ),
          _categoryList()
        ],
      ),
    );
  }

  Widget _categoryList() {
    return FutureBuilder(
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.hasData) {
          return __buildCategoryList(snapshot.data);
        }
        return Center(
          child: CircularProgressIndicator(),
        );
      },
    );
  }

  Widget __buildCategoryList(List<Categories> categories) {
    return Container(
      height: 150,
      alignment: Alignment.centerLeft,
      child: ListView.builder(
          shrinkWrap: true,
          physics: ClampingScrollPhysics(),
          scrollDirection: Axis.horizontal,
          itemCount: categories.length,
          itemBuilder: (context, index) {
            var data = categories[index];
            return Column(
              children: [
                Container(
                  margin: EdgeInsets.all(8.0),
                  width: 80,
                  height: 150,
                  alignment: Alignment.center,
                  /* child: Image.network(
                    data.image.url,
                    height: 80,
                  ), */
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        offset: Offset(0, 5),
                        blurRadius: 15,
                      ),
                    ],
                  ),
                ),
                Row(
                  children: <Widget>[
                    Text(data.categoryName.toString()),
                    Icon(Icons.keyboard_arrow_right, size: 14),
                  ],
                ),
              ],
            );
          }),
    );
  }
}

Here is my Categories.dart

import 'dart:ui';

class Categories {
  int categoryId;
  String categoryName;
  String categoryDesc;
  int parent;
  Image image;

  Categories({
    this.categoryId,
    this.categoryName,
    this.categoryDesc,
    this.parent,
    this.image,
  });

  Categories.fromJson(Map<String, dynamic> json) {
    categoryId = json['id'];
    categoryName = json['name'];
    categoryDesc = json['description'];
    parent = json['parent'];
    image = json['image'] != null ? new Image.fromJson(json['image']) : null;
  }
}

class Image {
  String url;

  Image({
    this.url,
  });

  Image.fromJson(Map<String, dynamic> json) {
    url = json['src'];
  }
}


Here is my apiservice.dart

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
//import '../models/categories.dart';
import 'config.dart';
import 'models/categories.dart';
//import '../model/login_model.dart';

class APIService {
  Future<List<Categories>> getCategories() async {
    List<Categories> data = new List<Categories>();

    try {
      String url = Config.url +
          "?consumer_key = ${Config.key}&consumer_secret=${Config.secret}";
      var response = await Dio().get(
        url,
        options: new Options(headers: {
          HttpHeaders.contentTypeHeader: "application/json",
        }),
      );

      if (response.statusCode == 201) {
        data = (response.data as List)
            .map(
              (i) => Categories.fromJson(i),
            )
            .toList();
      }
    } on DioError catch (e) {
      print('Error 404');
    }
  }
}

/* Future<LoginResponseModel> login(LoginRequestModel requestModel) async {
    String url = "https://reqres.in/api/login";

    final response = await http.post(url, body: requestModel.toJson());
    if (response.statusCode == 200 || response.statusCode == 400) {
      return LoginResponseModel.fromJson(
        json.decode(response.body),
      );
    } else {
      throw Exception('Failed to load data!');
    }
  }



  // ======= Category Mapping ============ //

  //Future<List<Category>> getCategories() async {
    List<Category> data = new List<Category>();

    try {
      String url = Config.url +
      "?consumer_key = ${Config.key}&consumer_secret=${Config.secret}";
      var response = await Dio(),get(
        url,
        options: new Options(
          header: {
            HttpHeaders.contentTypeheader: "application/json",
          }
        ),
      );

      if(response.statusCode == 201){
        
        
      }
    }
  } */

I dont know whats happening i am trying to show the categories in the homepage but it just showing the loading and it stills loading. I am fully stuck here.

1

There are 1 best solutions below

0
On

Woocommerce sends the response of 200 and after getting the data, you are not returning the data in getCategories(). The code is as follows:

try {
  String url = Config.url +
      Config.categoryUrl +
      "?consumer_key=${Config.consumerKey}&consumer_secret=${Config.consumerSecret}";

  var response = await Dio().get(
    url,
    options: Options(
      headers: {HttpHeaders.contentTypeHeader: 'application/json'},
    ),
  );
  if (response.statusCode == 200) {
    data = (response.data as List)
        .map(
          (i) => Category.fromJson(i),
        )
        .toList();
  }
} on DioError catch (e) {
  // ignore: avoid_print
  print(e.response);
}
return data;