0

I created an api that counts total category in my database table using laravel, and am trying to consume it in flutter and display the total count value. Please how can i achieve that

My Code:

//Laravel Query that count

public function count_categories(){

    $count_category = DB::table('category_menu')
    ->count();

   return response()->json($count_category);
}

//Flutter Code

//API URL

static const COUNT_CATEGORY = "/count_category";


  Future<List<Category>> countCategory() async {
    String countCategory = COUNT_CATEGORY;
    Map<String, String> headers = {'Accept': 'application/json'};
    var response = await http.get(countCategory, headers: headers);

    if (response.statusCode == 200) {
      var body = jsonDecode(response.body);
     
      print(response.body);
    }
  }

//The response.body is printing the count value correctly, how can i display the response body result in a class widget?

Otis
  • 339
  • 2
  • 16

2 Answers2

0

If I correctly understand what you are trying to do here is serialize the json response and then pass it onto a Widget.

Although more details on your objective would be useful, here it goes

There are many ways of doing it but the most basic approach is to use the json_serializable or the online converter.

For some reference refer to this answer here.

Once you convert your json response to a Dart Class (which might look something like)

class SampleModel {
  String name;
  int count;

  SampleModel({this.name, this.count});

  // You use this function to make a instance
  // of class SampleModel and use it inside an UI Widget
  SampleModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    count = json['count'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['count'] = this.count;
    return data;
  }

}

Now you can either use a FutureBuilder, setState() or a proper statemanagement solution to load this into a Widget.

class SampleWidget extends StatelessWidget {
  
  SampleWidget({this.model})
  
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(model.count),
    );
  }
}
DeprecatedAPI
  • 125
  • 1
  • 11
0

First of all, from what I see, from the API you are sending the amount (number), therefore when making the GET request from flutter you will receive a number in the body.

All good so far, but you must modify the data type of the function, you currently have defined:

Future<List<Category>> countCategory() async {...}

You must modify it for this if you want to return the value.

Future<int> countCategory() async {...}

Now, it can also be of type void, but you must save the value in a variable and then use this variable in the corresponding widget.

Future<void> countCategory() async {
 ...
 setState(() {
  count = response.body; // Assuming the variable is globally defined.
 })
}
Felipe Vergara
  • 849
  • 7
  • 12