Home > Blockchain >  convert object to map when object contains another class's object in flutter
convert object to map when object contains another class's object in flutter

Time:10-14

I want to convert object to map as key, value pair when an object contains another class's object...so here I don't know how to make a method named toMap here is my class structure

class Category
{
  String title;
  String iconurl;
  Category({required this.title, required this.iconurl});
  
  Map<String,dynamic> toMap()
  {
    return {
      'title':title,
      'iconurl':iconurl,
    };
  }
}

class Transaction
{
  String id;
  Category category;
  String paymentmode;
  bool isexpense;
  DateTime date;
  String note;
  double amount;
  Transaction({this.amount=0.00,required this.id, required this.category,required this.paymentmode, this.isexpense=true,required this.date,this.note='No Note'});

  Map<String,dynamic> tomap()
  {
    //what is the code for converting object to map
    //confused as object containing another class's object...
    return {

    };
  }
}

CodePudding user response:

You can use https://app.quicktype.io to create classes from json

// To parse this JSON data, do
//
//     final welcome = welcomeFromJson(jsonString);

import 'package:meta/meta.dart';
import 'dart:convert';

Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));

String welcomeToJson(Welcome data) => json.encode(data.toJson());

class Welcome {
    Welcome({
        @required this.id,
        @required this.category,
        @required this.paymentmode,
        @required this.isexpense,
        @required this.date,
        @required this.note,
        @required this.amount,
    });

    final String id;
    final Category category;
    final String paymentmode;
    final bool isexpense;
    final String date;
    final String note;
    final int amount;

    factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        id: json["id"],
        category: Category.fromJson(json["category"]),
        paymentmode: json["paymentmode"],
        isexpense: json["isexpense"],
        date: json["date"],
        note: json["note"],
        amount: json["amount"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "category": category.toJson(),
        "paymentmode": paymentmode,
        "isexpense": isexpense,
        "date": date,
        "note": note,
        "amount": amount,
    };
}

class Category {
    Category({
        @required this.title,
        @required this.iconurl,
    });

    final String title;
    final String iconurl;

    factory Category.fromJson(Map<String, dynamic> json) => Category(
        title: json["title"],
        iconurl: json["iconurl"],
    );

    Map<String, dynamic> toJson() => {
        "title": title,
        "iconurl": iconurl,
    };
}

  • Related