Class has no instance method error in flutter when displaying data in grouped listview from shared preferences

207 Views Asked by At

I'm trying to display stored bookmarks in a grouped listview but getting this error:

Class 'Bookmark' has no instance method '[]'.
Receiver: Instance of 'Bookmark'
Tried calling: []("surah_name")

The bookmarks are stored in shared preferences so we need to to fetch them on page load and display them in a listview grouped by surah name. I'm able to do it with a static list but unable to do it with a dynamic list and a futureBuilder.

The data that's coming from the shared preferences looks like this:

[{"surah_no":2,"verse_no":2,"surah_name":"Al-Baqarah","favorite":true}, {"surah_no":2,"verse_no":1,"surah_name":"Al-Baqarah","favorite":true}, {"surah_no":2,"verse_no":2,"surah_name":"Al-Baqarah","favorite":true}, {"surah_no":2,"verse_no":3,"surah_name":"Al-Baqarah","favorite":true}, {"surah_no":4,"verse_no":1,"surah_name":"An-Nisa'","favorite":true}, {"surah_no":8,"verse_no":1,"surah_name":"Al-Anfal","favorite":true}, {"surah_no":6,"verse_no":1,"surah_name":"Al-'An'am","favorite":true},...]

The code right now is :

class Bookmark {

  final int surah_no, verse_no;
  final String surah_name;
  bool favorite;

  Bookmark({this.surah_no, this.verse_no, this.surah_name, this.favorite});

  Bookmark.fromJson(Map<String, dynamic> jsonData)
      :
        surah_no = jsonData['surah_no'],
        verse_no = jsonData['verse_no'],
        surah_name= jsonData['surah_name'],
        favorite = jsonData['favorite'];

  Map<String, dynamic> toJson() =>
      {
        'surah_no': surah_no,
        'verse_no': verse_no,
        'surah_name': surah_name,
        'favorite': favorite,
      };

}



class _BookmarkScreenState extends State<BookmarkScreen> {

List bookmarks=[];
  List<Bookmark> bks = <Bookmark>[];
  Bookmark b = new Bookmark();


  @override
  void initState() {
    super.initState();
    _loadData();
    setState(() {

    });

  }

  Future<List<Bookmark>> _loadData() async {
    bookmarks.clear();
    SharedPreferences pref = await SharedPreferences.getInstance();
    List<String> lb = await pref.getStringList(('bookmarks_key'));
    print(lb);

lb.forEach((element) {bookmarks.add(element);});
    bks = bookmarks.map((s) => Bookmark()).toList();

    print(bks);
    return bks;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("Bookmark Screen")),
        body: Container(
            child: FutureBuilder(
                future: _loadData(),
                builder: (context, AsyncSnapshot snapshot) {
                  if (!snapshot.hasData) {
                    return Center(child: CircularProgressIndicator());
                  } else {
                    return GroupedListView<dynamic, String>(
                        elements: bks,
                        groupBy: (element) => element['surah_name'],
                        groupComparator: (value1, value2) => value2.compareTo(value1),
                        itemComparator: (item1, item2) =>
                            item1['verse_no'].compareTo(item2['verse_no']),
                        order: GroupedListOrder.DESC,
                        useStickyGroupSeparators: true,
                        groupSeparatorBuilder: (String value) => Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text(
                              value,
                              textAlign: TextAlign.center,
                              style:
                              TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                            )),
                        itemBuilder: ((c, element) {
                          return Card(
                            elevation: 8.0,
                            margin: new EdgeInsets.symmetric(
                                horizontal: 10.0, vertical: 6.0),
                            child: Container(
                              child: ListTile(
                                contentPadding: EdgeInsets.symmetric(
                                    horizontal: 20.0, vertical: 10.0),
                                title: Text(element['verse_no'].toString()),
                              ),
                            ),
                          );
                        }));}})));
  }
}

Please help me solve this error. Thank you

0

There are 0 best solutions below