0

我想在我的班级中传递数据并使用共享偏好将它们保存在地图上。并在另一个班级阅读我的数据。我的问题是关于保存地图和多次传递数据。那么如何在我的应用程序中保存地图列表?

这是我的代码,但我认为它是错误的:

class DownloadAudio extends StatefulWidget {
  final String audioUrl;
  final String imageUrl;
  final String title;

  const DownloadAudio(
      {Key? key,
      required this.audioUrl,
      required this.imageUrl,
      required this.title})
      : super(key: key);

  @override
  _DownloadAudioState createState() => _DownloadAudioState();
}

class _DownloadAudioState extends State<DownloadAudio> {
 Map<String,String> episodesData = {
   "image" : "",
   "audio" : "",
   "title" : ""
  }
  ;

    saveEpisodesList(Map episodesList) async {
    SharedPreferences pathEpisodesList = await SharedPreferences.getInstance();
    Map<String, dynamic> json = {'list': episodesList};
    pathEpisodesList.setString('EpisodesList', jsonEncode(json));
    episodesData = await getEpisodesList();
    // return episodesData;
  }

  getEpisodesList() async {
    SharedPreferences pathEpisodesList = await SharedPreferences.getInstance();
    if (pathEpisodesList.getString('EpisodesList') == "[]") {
    } else {
      episodesData = await json
          .decode(pathEpisodesList.getString('EpisodesList')!)['list'];
      return episodesData;
    }
  }

 @override
  Widget build(BuildContext context) {
     Map<String,String> episodesList = {
  "image" :  widget.title  ,
  "audio" :   widget.audioUrl ,
  "title" :   widget.imageUrl  ,
};
    saveEpisodesList(episodesList);
    return IconButton(
            icon: SvgPicture.asset(MyIcons.frame),
            onPressed:() async{
              downloadFile();
            },
          );
  }
}

任何人都可以帮助我吗?

4

1 回答 1

0
  1. 如果只想在类之间传递数据,可以使用静态字段。(因为通过共享首选项(sp)保存和检索数据可能会稍微降低性能+必须做更多的工作)

  2. 如果您只想使用 sp 您可以将地图列表转换为字符串并保存。

SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('key', "$list");

并获得清单: -

List<Map<..,..>> foo = prefs.getString('key') as List<Map>;
于 2022-01-06T11:57:12.883 回答