Search code examples
flutterdartflutter-getx

Flutter GetX - Integrate an API in the UI


I am a flutter beginner. Using Dart language. I am trying to integrate API with UI in Flutter using GetX. But while retrieving the product from the JSON file I got the below errors.

  1. `static Future fetchProducts() async {

error in fetch products - "The body might complete normally, causing 'null' to be returned, but the return type, 'FutureOr', is a potentially non-nullable type."

  1. var response = await client.get('https://............/');

error in the Uri - "The argument type 'String' can't be assigned to the parameter type 'Uri'."

Product Code:

ProductModel productFromJson(String str) => ProductModel.fromJson(json.decode(str));

String productToJson(ProductModel data) => json.encode(data.toJson());


class ProductModel{

ProductModel({
    required this.id,
    required this.title,
    required this.description,
    required this.price,
    required this.discountPercentage,
    required this.rating,
    required this.stock,
    required this.brand,
    required this.category,
    required this.thumbnail,
    required this.images,
});
int id;
String title;
String description;
int price;
double discountPercentage;
double rating;
int stock;
String brand;
String category;
String thumbnail;
List<String> images;

factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
    id: json["id"],
    title: json["title"],
    description: json["description"],
    price: json["price"],
    discountPercentage: json["discountPercentage"]?.toDouble(),
    rating: json["rating"]?.toDouble(),
    stock: json["stock"],
    brand: json["brand"],
    category: json["category"],
    thumbnail: json["thumbnail"],
    images: List<String>.from(json["images"].map((x) => x)),
);

Map<String, dynamic> toJson() => {
    "id": id,
    "title": title,
    "description": description,
    "price": price,
    "discountPercentage": discountPercentage,
    "rating": rating,
    "stock": stock,
    "brand": brand,
    "category": category,
    "thumbnail": thumbnail,
    "images": List<dynamic>.from(images.map((x) => x)),
};

}

API code:

import 'package:http/http.dart' as http;
import 'package:practice/productmodule/models/product_model.dart';

class ApiService {
static var client = http.Client();
static Future<ProductModel> fetchProducts() async {
var response = await client.get('https://.......1');
if (response.statusCode == 200) {
  var jsonString = response.body;
  return productFromJson(jsonString);
}

} }

Can anyone help me? Thanks in advance!


Solution

  • You have to change

    var response = await client.get('https://.......1');
    

    This with

    var response = await client.get(Uri.parse('https://.......1'));
    

    Because Http Client need Uri instead of String.