Created
March 13, 2022 15:09
-
-
Save evanca/5ab4ba6c63f972424d9ad9bceeed5344 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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