Home > Back-end >  Cannot Convert List<dynamic> to Map<String , dynamic>
Cannot Convert List<dynamic> to Map<String , dynamic>

Time:02-18

I am trying to add data from api as List to Map<String, dynamic> to add data to object of model

Pic of Cubit Pic of Cubit

this is error

this is error

CodePudding user response:

In summary, this happens because your API response data is a List and ProductModel.formJson is expecting a Map value.

You problably want all your products, no only one. Sooo... try something like this:

DioHelper.getData(path: 'products').then(
  (response) {
    final rawProductsList = response.data as List? ?? [];
    final productsList = rawProductsList.map(
       (rawProduct) => ProductModel.fromJson(rawProduct)
    );
    // continue your logic...
  }
)

CodePudding user response:

Based on the question and the small code.

ProductModel.dart Sample

class productModel {
  String? name;
  String? price;
  String? category;

  productModel({this.name, this.price, this.category});

  productModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    price = json['price'];
    category = json['category'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['price'] = this.price;
    data['category'] = this.category;
    return data;
  }
}

Here We notice the return type is future<dynamic> in both method.so we did'nt get any compile time error.while running application we get the error.

Diohelper.dart service

class Diohelper {
  static Future<dynamic> getdata({products}) {
    List list = [];
    list.add('{"name": "broast","price": "12","category": "chicken" }');
    list.add('{"name": "mandi","price": "102","category": "chicken" }');
    list.add('{"name": "mandi","price": "100","category": "veg" }');

    return Future.value(list);
  }
// static Future<dynamic> getdata({products}) {
//   List<productModel> list = [];
//   list.add(productModel(name: "broast", price: "100", category: "chicken"));
//   list.add(productModel(name: "mandi", price: "100", category: "chicken"));
//   list.add(productModel(name: "mandi", price: "100", category: "veg"));
//
//   return Future.value(list);
// }
}

enter image description here

Problem here productModel.fromJson(value.data);.Value.data is List<dynamic> .fromjson method need map<String,dynamic> type.

Solution:

enter image description here

    Diohelper.getdata(products: 'products').then((value) {
         
    
          var s = value as List;
          List<productModel> products = [];
          s.forEach((element) {
//------------------------here we converting json string to map object-------
            Map<String, dynamic> ma = jsonDecode(element);
            products.add(productModel.fromJson(ma));
          });
    
          print(products);
        });

full code:

import 'dart:convert';

import 'package:flutter/material.dart';

void main() =>
    runApp(MaterialApp(home: Scaffold(appBar: AppBar(), body: sta())));

class sta extends StatelessWidget {
  const sta({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Diohelper.getdata(products: 'products').then((value) {
      // productModel.fromJson(value);

      var s = value as List;
      List<productModel> products = [];
      s.forEach((element) {
        Map<String, dynamic> ma = jsonDecode(element);
        products.add(productModel.fromJson(ma));
      });

      print(products);
    });

    return GestureDetector(
      child: Center(
        child: Stack(
          children: [
            Container(
              height: double.infinity,
              width: double.infinity,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  fit: BoxFit.cover,
                  image: NetworkImage(
                    "https://st2.depositphotos.com/3759967/5593/i/600/depositphotos_55936567-stock-photo-swirling-frosty-multi-colored-fractal.jpg",
                  ),
                ),
              ),
            ),
            Positioned(
              bottom: MediaQuery.of(context).size.height * 0.1,
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      margin: const EdgeInsets.only(bottom: 10.0),
                      color: Colors.grey,
                      child: Column(children: const [
                        Icon(Icons.arrow_forward_sharp, size: 64),
                        Text('مشاركة')
                      ]),
                    ),
                    Container(
                      margin: const EdgeInsets.only(bottom: 10.0),
                      color: Colors.grey,
                      child: Column(children: const [
                        Icon(Icons.download_sharp, size: 64),
                        Text('مشاركة')
                      ]),
                    ),
                    Container(
                      margin: const EdgeInsets.only(
                        bottom: 10.0,
                      ),
                      color: Colors.grey,
                      child: Column(children: const [
                        Icon(
                          Icons.message,
                          size: 64,
                        ),
                        Text('مشاركة')
                      ]),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 8.0, right: 16),
                      child: Container(
                        height: 5,
                        width: 330,
                        child: LinearProgressIndicator(
                          value: 100,
                          backgroundColor: Colors.white,
                        ),
                      ),
                    ),
                  ]),
            ),
          ],
        ),
      ),
    );
  }
}

class productModel {
  String? name;
  String? price;
  String? category;

  productModel({this.name, this.price, this.category});

  productModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    price = json['price'];
    category = json['category'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['price'] = this.price;
    data['category'] = this.category;
    return data;
  }
}

class Diohelper {
  static Future<dynamic> getdata({products}) {
    List list = [];
    list.add('{"name": "broast","price": "12","category": "chicken" }');
    list.add('{"name": "mandi","price": "102","category": "chicken" }');
    list.add('{"name": "mandi","price": "100","category": "veg" }');

    return Future.value(list);
  }
// static Future<dynamic> getdata({products}) {
//   List<productModel> list = [];
//   list.add(productModel(name: "broast", price: "100", category: "chicken"));
//   list.add(productModel(name: "mandi", price: "100", category: "chicken"));
//   list.add(productModel(name: "mandi", price: "100", category: "veg"));
//
//   return Future.value(list);
// }
}
  • Related