Search code examples
jsonfluttercarousel-slider

how to get iamge from diffrent data api in flutter like this


I have my model for json, service to get api I just dont know how to get image like this like this from this json from this the Ipone Mega is the carousel slider(4 images in json link), below the other is just column if you could show it in carousel Slider i will be very grateful to you

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_work/apiService/fetch_data.dart';
import 'package:my_work/apiService/phone.dart';


class CarouselSliderData extends StatefulWidget{
  const CarouselSliderData({super.key});


  @override
  State<CarouselSliderData> createState() => CarouselSliderDataState();
}

class CarouselSliderDataState extends State<CarouselSliderData> {
  Phone? info;
   @override
  void initState() {
       DioService.getDataMocky(
           url:'https://run.mocky.io/v3/654bd15e-b121-49ba-a588-960956b15175'
       ).then((value) async {
         if(value != null){
           setState((){
             info = value!;
           });
         }
       }).catchError(
             (value) => (value),
       );

    super.initState();
  }


  @override
  Widget build(BuildContext context) {
     return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Image(image:)
                ],
              );



       }
}

Solution

  • Step 1: get the json from API. I call this variable is

    Map<String, dynamic> json;

    Step 2: As you can see, "home_store" of your json is a list of phones. Therefore, you create a model class called PhoneModel like this:

    class PhoneModel {
      int id;
      bool isNew;
      String title;
      String subtitle;
      String picture;
      bool isBuy;
    
      /// constructor
      PhoneModel({this.id ...});
    
      /// from json to class model
      PhoneModel.fromJson(Map<String, dynamic> json) {
        this.id = json["id"];
        this.isNew = json["is_new"];
        ...
      }
    }
    

    Then do like this to catch the list of items:

    List<PhoneModel> listPhones =  List<PhoneModel>.from(
      (json['home_store'] as List).map((e) => PhoneModel.fromJson(e)),
    );
    

    Now your list of phone is variable listPhones. Url is field picture. Do Image.network or anythings else... Good luck!