Reputation: 123
I want to pass data in my class and save them on the map with shared preferences. and read my data in another class. my problem is about saving the map and passing data more than once. so how can I save the list of maps in my app?
this is my code but I think its wrong:
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();
},
);
}
}
can anyone help me, please?
Upvotes: 0
Views: 939
Reputation: 206
If you just want to pass data between classes, you can use static fields. (As saving and retrieving data through shared preferences(sp) might reduce performance a little bit + would have to do more work)
If you just want to use sp you can convert the list of maps to string and save it.
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('key', "$list");
And to get the list:-
List<Map<..,..>> foo = prefs.getString('key') as List<Map>;
Upvotes: 0