I am trying to fetch data from api and show in list or card view

135

I think this might fix your issue:

  extractedData.forEach((element){
    loadedProduct.add(CategoryModel(
      id:element['id'],
      image:element!['images'],
      name:element['name'],
    ));

Let me know if you have any more issues.

Share:
135
Saurav
Author by

Saurav

Updated on January 03, 2023

Comments

  • Saurav
    Saurav over 1 year

    enter code here#in extractedData data is fetched but i am getting an error saying I/flutter ( 7967): type '(dynamic, dynamic) => Null' is not a subtype of type '(dynamic) => dynamic' of 'f' E/flutter ( 7967): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '(dynamic, dynamic) => Null' is not a subtype of type '(dynamic) => dynamic' of 'f' E/flutter ( 7967): #0 CategoryModels.fetchData (package:apiwork/models/category_model.dart:64:7) E/flutter ( 7967):

      Future<void> fetchData() async{
        var url = "my api goes here..........";
        try{
          final response = await http.get(Uri.parse(url));
          final extractedData = json.decode(response.body);
          final List<CategoryModel> loadedProduct = [];
          if(extractedData == null){
            return;
          }
          extractedData.forEach((prodId,productData){
            loadedProduct.add(CategoryModel(
              id:productData['id'],
              image:productData['images'],
              name:productData['name'],
            ));
          });
          _cItems = loadedProduct;
          notifyListeners();
          print(_cItems);
        }catch(e){
          print(e);
          throw e;
        }
      }
    

    #this is my home.dart

    class HomeScreen extends StatefulWidget {
      const HomeScreen({Key? key}) : super(key: key);
    
      @override
      _HomeScreenState createState() => _HomeScreenState();
    }
    
    class _HomeScreenState extends State<HomeScreen> {
      bool _selected =false;
      var _selectedIndex = 1;
      var _isInit = true;
      var _isLoading = false;
    
      @override
      void didChangeDependencies(){
        // TODO: implement didChangeDependencies
        if(_isInit){
          setState(() {
            _isLoading = true;
          });
          Provider.of<CategoryModels>(context).fetchData();
          setState(() {
            _isLoading = false;
          });
        }
        _isInit = false;
        super.didChangeDependencies();
      }
    
      void changeAnimatedContainerHeight(bool index){
        setState(() {
          _selected = index;
          _selected = !_selected;
          print(_selected);
        });
      }
    
      void onTapped(var index){
        setState(() {
          _selectedIndex = index;
        });
      }
      final List<String> imageList = [
        'https://th.bing.com/th/id/OIP.ayY5Ok1_cnPjwSRxEQERuwHaEO?pid=ImgDet&w=698&h=399&rs=1',
        'https://2qcolg3kl2ha3kfo912rzv2v-wpengine.netdna-ssl.com/wp-content/uploads/sites/8/2017/01/food-1400x550.jpg',
        'https://th.bing.com/th/id/OIP.qIMnTRibgveVBeUXxEQwngHaE1?pid=ImgDet&w=1024&h=669&rs=1'
      ];
    
    
      @override
      Widget build(BuildContext context) {
    
    
        return GestureDetector(
          onTap: (){
            FocusManager.instance.primaryFocus?.unfocus();
          },
    
          child: Scaffold(
            resizeToAvoidBottomInset: false,
            appBar: AppBar(
              backgroundColor: Colors.transparent,
              leading: const Icon(Icons.location_on_outlined,color: Colors.black,),
              // title: const Text('Chitwan',style: TextStyle(color: Colors.black),),
              elevation: 0,
              actions: [
                Padding(
                  padding: const EdgeInsets.only(right: 150.0,top: 5.0),
                  child: DropdownButton(
                    value:_selectedIndex,
                    items:const [
                      DropdownMenuItem(
                        child: Text("Chitwan"),
                        value: 1,
                      ),
                      DropdownMenuItem(
                        child: Text("Kathmandu"),
                        value: 2,
                      ),
                      DropdownMenuItem(
                        child: Text("Pokhara"),
                        value: 3,
                      ),
                      DropdownMenuItem(
                        child: Text("Butwal"),
                        value: 4,
                      ),
                      DropdownMenuItem(
                        child: Text("Hetauda"),
                        value: 5,
                      ),
                    ],
                    onChanged: onTapped,
                  ),
                ),
                // PopupMenuButton(itemBuilder: (BuildContext context){
                //   return[
                //     PopupMenuItem(child: InkWell(
                //       onTap: (){},
                //       child: Text("Chitwan"),
                //     )
                //     ),
                //     PopupMenuItem(child: InkWell(
                //       onTap: (){},
                //       child: Text("Kathmandu"),
                //     )
                //     ),
                //     PopupMenuItem(child: InkWell(
                //       onTap: (){},
                //       child: Text("Pokhara"),
                //     )
                //     ),
                //     PopupMenuItem(child: InkWell(
                //       onTap: (){},
                //       child: Text("Butwal"),
                //     )
                //     ),
                //     PopupMenuItem(child: InkWell(
                //       onTap: (){},
                //       child: Text("Hetauda"),
                //     )
                //     ),
                //   ];
                // }),
                IconButton(onPressed: (){
                  Provider.of<AuthProvider>(context,listen: false).logout(context);
                }, icon: const Icon(Icons.person,color: Colors.black,)),
                IconButton(onPressed: (){}, icon: const Icon(Icons.shopping_cart_outlined,color: Colors.black,)),
              ],
            ),
            // drawer: AppDrawer(),
            // body:BottomNavigation()
            body: SingleChildScrollView(
              scrollDirection: Axis.vertical,
              child: Column(
                  children: [
                    Form(
                      child: Padding(
                        padding: const EdgeInsets.only(left:2.0),
                        child: Container(
                          height: 45.0,
                          width: 380.0,
                          decoration:const BoxDecoration(
                            color: Color(0xFFF2F3F7),
                          ),
                          child: TextFormField(
                            decoration: const InputDecoration(
                                border: OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                ),
                                icon: Padding(
                                  padding: EdgeInsets.only(left: 5.0),
                                  child: Icon(Icons.search),
                                ),
                                hintText:'Hi, how can i help you?',
                                hintStyle: TextStyle(fontSize: 14.0)
                            ),
                          ),
                        ),
                      ),
                    ),
                    // const SizedBox(height: 10.0),
                    AnimatedContainer(
                      height:_selected?220:140,
                      decoration:const BoxDecoration(
                        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(40.0),bottomRight: Radius.circular(20.0)),
                        color: Colors.white,
                      ),
                      duration:  const Duration(seconds: 1),
                      curve: Curves.fastOutSlowIn,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          const Expanded(
                            child: SizedBox(
                              height:100.0,
                              child: Padding(
                                padding: EdgeInsets.only(top: 20.0),
                                child: CategoryGrid(),
                              ),
                            ),
                          ),
                          IconButton(onPressed:(){
                            changeAnimatedContainerHeight(_selected);
                          },  icon:Icon(_selected?Icons.expand_less:Icons.expand_more),color:Colors.black12,iconSize: 30.0,),
                        ],
                      ),
                    ),
                    const SizedBox(height: 10.0),
    
                    CarouselSlider(
                      items:imageList.map((e) =>ClipRRect(
                        borderRadius: BorderRadius.circular(8.0),
                        child: Stack(
                          fit: StackFit.expand,
                          children: [
                            Padding(
                              padding: const EdgeInsets.all(15.0),
                              child: Image.network(e,fit: BoxFit.cover),
                            )
                          ],
                        ),
                      ) ).toList()
                      , options: CarouselOptions(viewportFraction: 1,height: 140.0,autoPlay: true,autoPlayAnimationDuration: const Duration(milliseconds: 800),),),
    
                    const SizedBox(height: 10.0),
    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children:[
                        const Padding(
                          padding:EdgeInsets.only(right: 0.0),
                          child: Text("Today's Special",style: TextStyle(fontWeight: FontWeight.bold),),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 170.0),
                          child: GestureDetector(onTap: (){},child: const Text("More",style: TextStyle(color: Color(0xFFE10A35),fontWeight: FontWeight.w600),)),
                        ),
                        const Padding(
                          padding: EdgeInsets.only(right: 20.0),
                          child: Icon(Icons.chevron_right,color: Color(0xFFE10A35),),
                        ),
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
    
                    Row(
                      children: const [
                        Expanded(
                          child: SizedBox(
                            height:150.0,
                            child: Padding(
                              padding: EdgeInsets.only(left: 0),
                              child:TodaySpecialGrid(),
                            ),
                          ),
                        )
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children:[
                        const Padding(
                          padding:EdgeInsets.only(right: 0.0),
                          child: Text("Our Partners",style: TextStyle(fontWeight: FontWeight.bold),),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 170.0),
                          child: GestureDetector(onTap: (){},child: const Text("More",style: TextStyle(color: Color(0xFFE10A35),fontWeight: FontWeight.w600),)),
                        ),
                        const Padding(
                          padding: EdgeInsets.only(right: 20.0),
                          child: Icon(Icons.chevron_right,color: Color(0xFFE10A35),),
                        ),
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
                    Row(
                      children: const [
                        Expanded(
                          child: SizedBox(
                            height:180.0,
                            child: Padding(
                              padding: EdgeInsets.only(left: 8.0),
                              child:OurPartnersGrid(),
                            ),
                          ),
                        )
                      ],
                    ),
    
    
                    const SizedBox(height: 10.0),
    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children:[
                        const Padding(
                          padding:EdgeInsets.only(right: 0.0),
                          child: Text("Our Hotels",style: TextStyle(fontWeight: FontWeight.bold),),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 170.0),
                          child: GestureDetector(onTap: (){},child: const Text("More",style: TextStyle(color: Color(0xFFE10A35),fontWeight: FontWeight.w600),)),
                        ),
                        const Padding(
                          padding: EdgeInsets.only(right: 20.0),
                          child: Icon(Icons.chevron_right,color: Color(0xFFE10A35),),
                        ),
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
                    Row(
                      children: const [
                        Expanded(
                          child: SizedBox(
                            height:180.0,
                            child: Padding(
                              padding: EdgeInsets.only(left: 8.0),
                              child:OurHotelGrid(),
                            ),
                          ),
                        )
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
    
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children:[
                        const Padding(
                          padding:EdgeInsets.only(right: 0.0),
                          child: Text("New Products",style: TextStyle(fontWeight: FontWeight.bold),),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 170.0),
                          child: GestureDetector(onTap: (){},child: const Text("More",style: TextStyle(color: Color(0xFFE10A35),fontWeight: FontWeight.w600),)),
                        ),
                        const Padding(
                          padding: EdgeInsets.only(right: 20.0),
                          child: Icon(Icons.chevron_right,color: Color(0xFFE10A35),),
                        ),
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
                    Row(
                      children: const [
                        Expanded(
                          child: SizedBox(
                            height:180.0,
                            child: Padding(
                              padding: EdgeInsets.only(left: 8.0),
                              child:NewProductGrid(),
                            ),
                          ),
                        )
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children:[
                        const Padding(
                          padding:EdgeInsets.only(right: 0.0),
                          child: Text("Vegetables",style: TextStyle(fontWeight: FontWeight.bold),),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(left: 170.0),
                          child: GestureDetector(onTap: (){},child: const Text("More",style: TextStyle(color: Color(0xFFE10A35),fontWeight: FontWeight.w600),)),
                        ),
                        const Padding(
                          padding: EdgeInsets.only(right: 20.0),
                          child: Icon(Icons.chevron_right,color: Color(0xFFE10A35),),
                        ),
                      ],
                    ),
    
                    const SizedBox(height: 10.0),
                    Row(
                      children: const [
                        Expanded(
                          child: SizedBox(
                            height:500.0,
                            child: Padding(
                              padding: EdgeInsets.only(left: 8.0),
                              child:VegetableGrid(),
                            ),
                          ),
                        )
                      ],
                    ),
                    // const BottomNavigation()
                  ]),
            ),
    
          ),
        );
      }
    }
    
    • Raphael Sauer
      Raphael Sauer over 2 years
      I think your problem is that json.decode returns a dynamic object, and you are trying yo use it in the forEach with key, value pairs. Try iterating differently on the object (maybe a normal for loop) and see if it helps.
    • Saurav
      Saurav over 2 years
      actually i made two model main model is in another place which i made using quicktype and this categorymodel i made it myself according to the requirment on what to show on screen by fetching data from api and i tried different method but didnt work
  • Saurav
    Saurav over 2 years
    type 'List<dynamic>' is not a subtype of type 'List<Image>?' got this error
  • Raphael Sauer
    Raphael Sauer over 2 years
    In this line? image:element['images'],
  • Saurav
    Saurav over 2 years
    yes i think so from my api data image comes as images
  • Raphael Sauer
    Raphael Sauer over 2 years
    I think its a null check issue, I will modify the code above to check for nulls
  • Saurav
    Saurav over 2 years
    the above answer worked but my image is not loading
  • Saurav
    Saurav over 2 years
    in my api i have Image? image and i have different Image class and inside it there is src where image is loaded