kumar
kumar

Reputation: 111

parsing data in model class in dart _type error?

I am learning Dart and Flutter. Now I am tasting JSON as a persistence method. I get lots of errors, all concerning Types and stuff. This is the latest error I have experienced: _TypeError (type 'List' is not a subtype of type 'Map')

_TypeError (type 'String' is not a subtype of type 'Map')

static Resource<List<ProductImage>> get all {    
    return Resource(
      url: Constants.HEADLINE_NEWS_URL,
      parse: (response) {

    String jsonProduct = response.body;
     final jsonResponse = json.decode(jsonProduct);    
   Product product = new Product.fromJson(jsonResponse);   

        return product.images.toList();

      //return list.map((model) => NewsArticle.fromJson(model));

      }
    );
}

My Model :

        class Product {
        final String id; 
        final List<ProductImage> images;

      Product({this.id, this.images});

        factory Product.fromJson(Map<String, dynamic> parsedJson){

        var list = parsedJson['IDEPELTION'] as List;
        print(list.runtimeType);
        List<ProductImage> imagesList = list.map((i) => ProductImage.fromJson(i)).toList();


        return Product(
          id: parsedJson['DATAS'],
          images: imagesList

        );
      }


    }

    class ProductImage {
      final String itemName;
      final String iCategory;
     // bool isCheck;

      ProductImage({this.itemName, this.iCategory});

      factory ProductImage.fromJson(Map<String, dynamic> parsedJson){
       return ProductImage(
         itemName:parsedJson['ITEM_NAME'],
         iCategory:parsedJson['CATEGORY'],
         //isCheck:false
       );
      }
    }

this is my sample json return the list data to get all method

{"DATAS":"1","IDEPELTION":[{"ITEM_NAME":TRUEMETRIX ,"CATEGORY":"MOUTHPIECE"},{"ITEM_NAME":MULTISTIX 10SG 2161,"CATEGORY":"MOUTHPIECE"}]}

Upvotes: 0

Views: 533

Answers (2)

chunhunghan
chunhunghan

Reputation: 54397

You can copy paste run full code below
You can see related Product class in full code and parse with product = productFromJson(jsonString);

code snippet

String jsonString = '''
    {"DATAS":"1",
"IDEPELTION":
[{"ITEM_NAME":"TRUEMETRIX" ,
"CATEGORY":"MOUTHPIECE"},
{"ITEM_NAME":"MULTISTIX 10SG 2161",
"CATEGORY":"MOUTHPIECE"}]}
    ''';

product = productFromJson(jsonString);

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'dart:convert';

Product productFromJson(String str) => Product.fromJson(json.decode(str));

String productToJson(Product data) => json.encode(data.toJson());

class Product {
  String datas;
  List<Idepeltion> idepeltion;

  Product({
    this.datas,
    this.idepeltion,
  });

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        datas: json["DATAS"],
        idepeltion: List<Idepeltion>.from(
            json["IDEPELTION"].map((x) => Idepeltion.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "DATAS": datas,
        "IDEPELTION": List<dynamic>.from(idepeltion.map((x) => x.toJson())),
      };
}

class Idepeltion {
  String itemName;
  String category;

  Idepeltion({
    this.itemName,
    this.category,
  });

  factory Idepeltion.fromJson(Map<String, dynamic> json) => Idepeltion(
        itemName: json["ITEM_NAME"],
        category: json["CATEGORY"],
      );

  Map<String, dynamic> toJson() => {
        "ITEM_NAME": itemName,
        "CATEGORY": category,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Product product;
  void _incrementCounter() {
    String jsonString = '''
    {"DATAS":"1",
"IDEPELTION":
[{"ITEM_NAME":"TRUEMETRIX" ,
"CATEGORY":"MOUTHPIECE"},
{"ITEM_NAME":"MULTISTIX 10SG 2161",
"CATEGORY":"MOUTHPIECE"}]}
    ''';
    product = productFromJson(jsonString);
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            product == null
                ? Container()
                : Expanded(
                    child: ListView.builder(
                        padding: const EdgeInsets.all(8),
                        itemCount: product.idepeltion.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Container(
                            child: Center(
                                child: Text(
                                    '${product.idepeltion[index].category} ${product.idepeltion[index].itemName}')),
                          );
                        }),
                  ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 1

Peter Haddad
Peter Haddad

Reputation: 80934

Change:

String jsonProduct = response.body;

Into this:

Map<String,dynamic> jsonProduct = response.body;

Since the response is of type Map

Upvotes: 0

Related Questions