Home > Software engineering >  How do I display an image received from an API response in my app
How do I display an image received from an API response in my app

Time:11-16

I am using http package to make get request and fetch data from an API in flutter. But I cannot seem to understand how do I display an image in my app

Here is the code:

***Cars.dart***

Future<CartModel> fetchCartModel() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));

  if (response.statusCode == 200) {

    return CartModel.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load data');
  }
}

class Cars extends StatefulWidget {
  @override
  _CarsState createState() => _CarsState();
}
class _CarsState extends State<Cars> {
   Future<CartModel> futureCartModel;
   @override
   void initState() {
     super.initState();
     futureCartModel = fetchCartModel();
   }
    Container(
width: 180,
height: 139,
margin:EdgeInsets.all(5),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(''),
fit: BoxFit.fill,
),
),
),
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Here is the model class:

class CartModel {
  int albumId;
  int id;
  String title;
  String url;
  String thumbnailUrl;

  CartModel({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

  CartModel.fromJson(Map<String, dynamic> json) {
    albumId = json['albumId'];
    id = json['id'];
    title = json['title'];
    url = json['url'];
    thumbnailUrl = json['thumbnailUrl'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['albumId'] = this.albumId;
    data['id'] = this.id;
    data['title'] = this.title;
    data['url'] = this.url;
    data['thumbnailUrl'] = this.thumbnailUrl;
    return data;
  }
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I was able to get text data from the app but i cannot seem to understand how do I display the image that I am fetching from the API.

CodePudding user response:

The api response is a List of CartModel, not a single CartModel. You need to use FutureBuilder to fetch api data and show it through ListView.builder and put the thumbnail url for each item into the NetworkImage.

Code:

import 'dart:convert' as convert;

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:stacksolution/cart_model.dart';

class FetchData extends StatefulWidget {
  const FetchData({Key? key}) : super(key: key);

  @override
  _FetchDataState createState() => _FetchDataState();
}

class _FetchDataState extends State<FetchData> {
  @override
  void initState() {
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stack Over Flow'),
      ),
      body: FutureBuilder<List<CartModel>>(
        future: fetchApiData(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemBuilder: (context, index) {
                CartModel cartModel = snapshot.data![index];
                return Container(
                  width: 180,
                  height: 139,
                  margin: EdgeInsets.all(5),
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: NetworkImage(cartModel.thumbnailUrl!),
                      fit: BoxFit.fill,
                    ),
                  ),
                );
              },
              itemCount: snapshot.data!.length,
            );
          } else if (snapshot.hasError) {
            return Text('${snapshot.error}');
          }
          return CircularProgressIndicator();
        },
      ),
    );
  }

  Future<List<CartModel>> fetchApiData() async {
    final response = await http
        .get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));

    if (response.statusCode == 200) {
      List<dynamic> list = convert.jsonDecode(response.body);

      List<CartModel> cartList =
          list.map((e) => CartModel.fromJson(e)).toList();

      return cartList;
    } else {
      throw Exception('Failed to load data');
    }
  }
}

CodePudding user response:

You can use

Image.network('***your image url here*****')

CodePudding user response:

Try this one

Future<CartModel> fetchCartModel() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));

  if (response.statusCode == 200) {

 var decodedJson = json.decode(response.body) as List;

      return decodedJson.map((e) => CartModel.fromJson(e)).toList();  
} else {
    throw Exception('Failed to load data');
  }
}
  • Related