how to decode Json to DateTime format in flutter?

2,456

In Transaction.fromMap constructor

replace

this.date = map['date'],

with

this.date = DateTime.parse(map['date']),
Share:
2,456
azheen
Author by

azheen

Updated on December 19, 2022

Comments

  • azheen
    azheen over 1 year

    im trying to store my List data in a disk storage using shared preferences, however idk how to convert the json back to DateTime format when trying to fetch data again from memory when i rebuild/restart the app.

    here's my code:

      String id;
      String title;
      double amount;
      DateTime date;
    
      Transaction({
        @required this.id,
        @required this.title,
        @required this.amount,
        @required this.date,
      });
    
      Transaction.fromMap(Map map)
          : this.id = map['id'],
            this.title = map['title'],
            this.date = map['date'],
            this.amount = map['amount'];
    
      Map toMap() {
        return {
          'id': this.id,
          'title': this.title,
          'date': this.date.toIso8601String(),
          'amount': this.amount,
        };
      }
    }
    

    heres where im using sharedPreferences

    @override
      void initState() {
        initSharedPreferences();
        super.initState();
      }
    
      initSharedPreferences() async {
        sharedPreferences = await SharedPreferences.getInstance();
        loadData();
      }
    
    
      void saveData() {
        setState(() {
          List<String> spList =
              transactions.map((item) => json.encode(item.toMap())).toList();
          var list = sharedPreferences.setStringList('list', spList);
          print(list);
        });
      }
    
      void loadData() {
        List<String> spList = sharedPreferences.getStringList('list');
        transactions =
            spList.map((item) => Transaction.fromMap(json.decode(item))).toList();
        setState(() {});
        print(transactions);
      }