Bill Rei
Bill Rei

Reputation: 451

Flutter : How to create Favorite List from JSON

I am going to create a JSON data in my flutter application and allow users to choice what item that theirs favorite to. This is the class from Doa, and the data i take it from local JSON file.

import 'dart:convert';

List<Doa> doaFromJson(String str) =>
    List<Doa>.from(json.decode(str).map((x) => Doa.fromJson(x)));

String doaToJson(List<Doa> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Doa {
  Doa({
    this.id,
    this.grup,
    this.judul,
    this.lafaz,
    this.latin,
    this.arti,
    this.tentang,
    this.mood,
    this.tag,
    this.fav,
  });

  final int id;
  final String grup;
  final String judul;
  final String lafaz;
  final String latin;
  final String arti;
  final String tentang;
  final String mood;
  final String tag;
  bool fav;

  factory Doa.fromJson(Map<String, dynamic> json) => Doa(
        id: json["id"],
        grup: json["grup"],
        judul: json["judul"],
        lafaz: json["lafaz"],
        latin: json["latin"],
        arti: json["arti"],
        tentang: json["tentang"],
        mood: json["mood"],
        tag: json["tag"],
        fav: json["fav"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "grup": grup,
        "judul": judul,
        "lafaz": lafaz,
        "latin": latin,
        "arti": arti,
        "tentang": tentang,
        "mood": mood,
        "tag": tag,
        "fav": fav,
      };
}

And this is my main page that show the list of the JSON data.

import 'package:flutter/material.dart';
import 'package:json_test/class/doa.dart';
import 'package:json_test/page/DoaPage.dart';

class MainPage extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  List<Doa> doaList;
  bool _isInit = true;

  Future<void> fetchDoa(BuildContext context) async {
    final jsonstring =
        await DefaultAssetBundle.of(context).loadString('assets/doa.json');
    doaList = doaFromJson(jsonstring);
    _isInit = false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("JSON Data test"),
        ),
        body: Container(
            child: FutureBuilder(
                future: _isInit ? fetchDoa(context) : Future(null),
                builder: (context, _) {
                  if (doaList.isNotEmpty) {
                    return ListView.builder(
                      itemCount: doaList.length,
                      itemBuilder: (BuildContext context, int index) {
                        Doa doa = doaList[index];
                        return Card(
                            margin: EdgeInsets.all(8),
                            child: ListTile(
                                title: Text(doa.judul),
                                onTap: () {
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (BuildContext context) =>
                                          DoaPage(
                                            doa: doa,
                                          )));
                                },
                                trailing: IconButton(
                                  icon: Icon(
                                    doa.fav
                                        ? Icons.favorite
                                        : Icons.favorite_border,
                                    color: doa.fav ? Colors.red : null,
                                  ),
                                  onPressed: () =>
                                      setState(() => doa.fav = !doa.fav),
                                )));
                      },
                    );
                  }
                  return CircularProgressIndicator();
                })));
  }
}

The favorite button is worked. But, when I close the application, all of favorited items will be lost. The result from my code shown here my bug app

After I give some 'love' for the items, when I close the app and re-open it, all of favorited items will lost. Anyone can give me some advice for my code? Thank you very much.

Upvotes: 0

Views: 1103

Answers (1)

Said Kurt
Said Kurt

Reputation: 104

You should save the favorite item local phone or you can use apı service. you don't save the that item and when you close the application that item is a coming null

You can use this package for the save favorite item

shared_preferences 

or

 hive

Upvotes: 1

Related Questions