Add http to a missing url in flutter

1.1k Views Asked by At

Is there a way to add https extension hidden by CDN inside mapping in flutter? As you can see in the picture below I'd need to add as link inside my model JSON but the https is hidden by the CDN. How can I solve this issue in order to show up my image from that link? Thank you in advance.

enter image description here

Fetch page for article

class ApiNewsPage {
  String baseUrl = "https://www.assofacile.it/wp-json/wp/v2/posts?_embed";

  Future<List> getNewsArticles() async {
    try {
      var response = await http.get(Uri.parse(baseUrl));
      //print(response);
      if (response.statusCode == 200) {
        return jsonDecode(response.body);
      } else {
        return Future.error("Impossibile ricevere i dati, prova a controllare la connessione");
      }
      // ignore: non_constant_identifier_names
    } catch (SocketException) {
      return Future.error("Impossibile caricare gli articoli");
    }
  }
}

Model page for article

class Article{
  final String? urlImage;
  final String? title;
  final String? description;

  Article({
    required this.urlImage,
    required this.title,
    required this.description,
  });

  factory Article.fromJson(Map<String, dynamic> json) => Article(
    urlImage: json["_embedded"]["wp:featuredmedia"][0]["link"],
    title: json["title"]["rendered"],
    description: json['content']['rendered'],
  );

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};

    data['urlImage'] = urlImage;
    data['title'] = title;
    data['desciption'] = description;
    
    return data;
  }
}

Article content UI

SizedBox(
    height: 190,
    width: double.infinity,
    child: CachedNetworkImage(
      imageUrl: snapshot.data![i]["_embedded"]["wp:featuredmedia"][0]["link"],
                  fit: BoxFit.cover,
                  placeholder: (context, url) => Image.asset("assets/gif/shimmer.gif",
                  width: double.infinity,
                  height: 190,
                  fit: BoxFit.cover,
             ),
           errorWidget: (context, url, error) =>
      Image.asset("assets/images/unloadedImage.png", width: 250, height: 250),
   ),
),
1

There are 1 best solutions below

3
Will On

You can create a simple method like bellow and verify before using the url that you need

 String checkIfUrlContainPrefixHttp(String url) {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    } else {
      return 'http://' + url;
    }
  }