Skip to content

Instantly share code, notes, and snippets.

@evanca
Created March 13, 2022 15:09
Show Gist options
  • Save evanca/5ab4ba6c63f972424d9ad9bceeed5344 to your computer and use it in GitHub Desktop.
Save evanca/5ab4ba6c63f972424d9ad9bceeed5344 to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class HighScore {
final String username;
final int difficulty;
final int score;
HighScore(
{required this.username, required this.difficulty, required this.score});
Map<String, dynamic> toMap() {
return {
'username': username,
'difficulty': difficulty,
'score': score,
};
}
factory HighScore.fromMap(Map<String, dynamic> map) {
return HighScore(
username: map['username'] as String,
difficulty: map['difficulty'] as int,
score: map['score'] as int);
}
save() async {
final prefs = await SharedPreferences.getInstance();
String? initialHighScores = prefs.getString('highscores');
List currentHighScores = [];
Map map = toMap();
if (initialHighScores != null) {
currentHighScores = jsonDecode(initialHighScores);
}
currentHighScores.add(map);
currentHighScores.sort((a, b) => (b["score"]).compareTo(a["score"]));
// Keep 10 records max:
currentHighScores = currentHighScores.take(10).toList();
await prefs.setString('highscores', jsonEncode(currentHighScores));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment