Flutter:使用共享首选项插件存储保存的收藏夹列表

Flutter: using shared preferences plugin to store saved favorite list

以下是我的 JSON 文件,其中包含数据:

[
    {
        "city": "City1",
        "attractions": [
            "attraction1",
            "attraction2"
        ],
    },
    {
        "city": "city2",
        "attractions": [
            "attraction1",
            "attraction2",
        ],
    },
]

我的实现代码是一个列表视图生成器,它从 JSON 文件中获取数据。该代码还有一个选项,可以将城市保存为收藏夹,可以在另一个页面中显示为保存的收藏夹列表:

class Index extends StatefulWidget {
  @override
  _IndexState createState() => _IndexState();
}
List data;
List<Cities> citylist = List();
List<Cities> citysavedlist = List();
int index;
class _IndexState extends State<Index> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: listView(),
    );
  }
  Future<String> fetchData() async {
    String data =
        await DefaultAssetBundle.of(context).loadString("assets/data.json");
    final jsonResult = json.decode(data);
    this.setState(() {
      jsonResult
          .forEach((element) => citylist.add(new Cities.fromJson(element)));
    });
    return "Success!";
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  listView() {
    return ListView.builder(
      itemCount: citylist == null ? 0 : citylist.length,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[_buildRow(index, citylist)],
        );
      },
    );
  }

  Widget _buildRow(index, citylist) {
    final bool alreadySaved = citysavedlist.contains(citylist[index]);
    return Padding(
      padding: const EdgeInsets.only(top: 5.0, left: 5.0, right: 5.0),
      child: Card(
        child: ListTile(
            title:
                Text(citylist[index].title, style: TextStyle(fontSize: 22.0)),
            trailing: IconButton(
              icon: Icon(
                alreadySaved ? Icons.star : Icons.star_border,
                color: alreadySaved ? Colors.blue : Colors.blue,
              ),
              onPressed: () {
                setState(() {
                  if (alreadySaved) {
                    citysavedlist.remove(citylist[index]);
                  } else {
                    citysavedlist.add(citylist[index]);
                  }
                });
              },
            ), //subtitle: Text(subtitle),
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => Detail(citylist[index])));
            }),
      ),
    );
  }


void _pushSaved() {
    Navigator.of(context).push(
      MaterialPageRoute<void>(
        builder: (BuildContext context) {
          final Iterable<ListTile> tiles = citysavedlist.map(
            (Cities pair) {
              return ListTile(
                  title: Text(
                    pair.city,
                  ),
                  onTap: () {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => Detail(pair)));
                  });
            },
          );

          final List<Widget> divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();
          return Scaffold(
            appBar: AppBar(
              title: const Text('Saved Suggestions'),
            ),
            body: ListView(children: divided),
          );
        },
      ),
    );
  }
}

这是型号 class :

List<Cities> citiesFromJson(String str) =>
    List<Cities>.from(json.decode(str).map((x) => Cities.fromJson(x)));
String citiesToJson(List<Cities> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Cities {
  Cities({
    this.city,
    this.attractions,
  });

  String city;
  List<String> attractions;

  factory Cities.fromJson(Map<String, dynamic> json) => Cities(
        city: json["city"],
        attractions: List<String>.from(json["attractions"].map((x) => x)),
      );

  Map<String, dynamic> toJson() => {
        "city": city,
        "attractions": List<dynamic>.from(attractions.map((x) => x)),
      };
}

我现在面临一个问题,就是保存的收藏城市没有保存,所以当应用程序关闭并重新打开时,收藏列表会因为没有保存而消失。

我知道有一个名为 Shared preferences 的插件可以执行存储已保存数据的功能,但我无法将此插件集成到我的代码中。有人可以帮忙做吗。

首先你要做的是在 pubspec 中获取包然后

import 'package:shared_preferences/shared_preferences.dart';

SharedPreferences prefs = await SharedPreferences.getInstance();

现在要保存json数据你要做的是

prefs.setString('mydata', json.encode(yourjsondata));

检索此数据 你必须使用你指定的确切名称,在我的例子中 'mydata'

json.decode(preferences.getString('mydata'))

记住,如果你想保存这么多数据项,建议使用 sqflite 或 hive,或者如果你仍然想使用 shared_preferences,你可以将计数器保存为

保存

var counter = (prefs.getInt('Counter')??0)+1;
prefs.setString('Counter:$counter', json.encode(yourdata));

返回订单

var listCount = preferences.getInt('Counter');

循环使用 listCount 然后使用

json.decode(preferences.getString('Counter:$variable'))