bawantha geeganage
bawantha geeganage

Reputation: 3

How to display hardcode image on flutter which is not available in json link

I am new to flutter and I'm currently developing a flutter application that fetches data from https://private-anon-b242a842d4-carsapi1.apiary-mock.com/manufacturers. I am displaying the image and name from the above JSON file. some of the image URL s don't have images. How can I display an image from my assets folder except for the unavailable images in the JSON file?

Home Page - where i display list of images and names

  Future<List<Car>> fetchCar() async {
    carList = [];
    final response = await http.get(
      Uri.parse('https://private-anon-b242a842d4-carsapi1.apiary-mock.com/manufacturers')
    );
    if (response.statusCode == 200) {
      List<dynamic> values = [];
      values = json.decode(response.body);

      if (values.length > 0) {
        for (int i = 0; i < values.length; i++) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            carList.add(Car.fromJson(map));
          }
        }
        setState(() {
          carList;
        });
      }
      return carList;
    }else {
      throw Exception('Failed to load cars');
    }
  }

     @override
      void initState() {
        fetchCar();
        Timer.periodic(Duration(seconds: 10), (timer) => fetchCar());
        super.initState();
      }
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: ListView.builder(
              scrollDirection: Axis.vertical,
              itemCount: carList.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: (){
                    Navigator.of(context).push(MaterialPageRoute(builder: (_)=>DetailsPAge(
                      name: carList[index].name,
                      img_url: carList[index].img_url,
                      avg_price: carList[index].avg_price,
                      num_models:carList[index].num_models,
                      max_car_id: carList[index].max_car_id,
                      avg_horsepower: carList[index].avg_horsepower,
                )),);
              },
              child: CarCard(
                name: carList[index].name,
                img_url: carList[index].img_url
              ),
            );
          },
        ));
      }
    }
    
    class Car {
      Car({
        required this.name,
        required this.id,
        required this.img_url,
        required this.max_car_id,
        required this.num_models,
        required this.avg_price,
        required this.avg_horsepower
      });
    
      String name;
      int id;
      String img_url;
      int max_car_id;
      int num_models;
      double avg_horsepower;
      double avg_price;
    
      factory Car.fromJson(Map<String, dynamic> json) {
        return Car(
            name: json['name'],
            id: json['id'],
            img_url: json['img_url'],
            max_car_id: json['max_car_id'],
            num_models:json['num_models'],
            avg_price: json['avg_price'],
            avg_horsepower: json['avg_horsepower']
        );
      }
    }
    
    List<Car> carList = [];

CarCard widget - where I customize image and text

    class CarCard extends StatelessWidget {
      CarCard({
        required this.name,
        required this.img_url,
      });
    
      String name;
      String img_url;
    
      @override
      Widget build(BuildContext context) {
        return Padding(
          padding: const EdgeInsets.only(top: 15, left: 10, right: 10),
          child:  Container(
            height: 100,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.grey,
                  offset: Offset(4, 4),
                  blurRadius: 10,
                  spreadRadius: 1,
                ),
                BoxShadow(
                  color: Colors.white,
                  offset: Offset(-4, -4),
                  blurRadius: 10,
                  spreadRadius: 1,
                ),
              ],
            ),
            child: Row(
              children: [
                Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey,
                          offset: Offset(4, 4),
                          blurRadius: 10,
                          spreadRadius: 1,
                        ),
                        BoxShadow(
                          color: Colors.white,
                          offset: Offset(-4, -4),
                          blurRadius: 10,
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                    height: 60,
                    width: 60,
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Image.network(img_url),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        FittedBox(
                          fit: BoxFit.scaleDown,
                          child: Text(
                            name,
                            style: TextStyle(
                              color: Colors.grey[900],
                              fontSize: 25,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }

Upvotes: 0

Views: 476

Answers (2)

Jahidul Islam
Jahidul Islam

Reputation: 12565

If the image is not in json link, then you can check it first and then show from local assets, lets try

child: Padding(
  padding: const EdgeInsets.all(10.0),
  child: img_url!=null && img_url.isNotEmpty
    ? Image.network(img_url)
    : Icon(Icons.add),
),

instead of icon you can try with

Align(
  alignment: Alignment.center,
  child: Image.asset('images/ic_alert_triangle.png'),
),

Upvotes: 0

Viraj Doshi
Viraj Doshi

Reputation: 881

As far as I understood your question you want to display an image from your assets if there are no image in the json.
If that is what you want to do then you can use ?? operator, to check if there is an image in that json, like:

Navigator.of(context).push(MaterialPageRoute(builder: (_)=>DetailsPAge(
  name: carList[index].name,
  img_url: carList[index].img_url ?? Image.assets("<Your asset image path>"),
  avg_price: carList[index].avg_price,
  num_models:carList[index].num_models,
  max_car_id: carList[index].max_car_id,
  avg_horsepower: carList[index].avg_horsepower,
)),);

You can add this everywhere you want an image.

Also don't put all of your code no one is actually going to read and understand all of that; only add the code that is causing the error.

Upvotes: 1

Related Questions