Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List<T> into json in flutter

I have a list of option when the attribute is selected of a particular option then I save attribute object at the selected position of option in the list. now I have an option list with their selected attribute object. My aim is to convert the options list into JSON object but when the attribute is not null. The Attribute object can be null in that case when a person has not chosen an attribute of an option.

class OptionAttribute{
 String _grouprowid;
 String _groupname;
 Attribute _selectedAttrObject

   Map<String, dynamic> toJson() => {
    'attribute': _selectedAttrObject,
  };
}

class Attribute{

  String _attributerowid;
  String _grouprowid;
  String _attributename;
  String _weight;

   Map<String, dynamic> toJsonAttr() => {
    'attrid': _attributerowid,
    'groupid': _grouprowid,
    'attrname': _attributename
  };

}

I want to convert below list into JSON object when the list does not have any null attribute.

List<OptionAttribute> opAtrrList=new List<OptionAttribute>();
like image 268
Farhana Naaz Ansari Avatar asked Mar 08 '19 06:03

Farhana Naaz Ansari


People also ask

What is JSON encode in Flutter?

jsonEncode function Null safetyConverts object to a JSON string. If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.

How do you convert a list into a dart set?

In Dart, a list is an indexable collection of objects with a length while a set is a collection of objects where each object can occur only once. This short article shows you how to convert a list to a set and vice versa, turn a set into a list. The toSet() method helps us do the job.


1 Answers

You need to convert each item individually

var json = jsonEncode(opAttrList.map((e) => e.toJson()).toList());

or pass an toEncodable function

var json = jsonEncode(opAttrList, toEncodable: (e) => e.toJsonAttr());
like image 82
Günter Zöchbauer Avatar answered Oct 06 '22 20:10

Günter Zöchbauer