Skip to content

Instantly share code, notes, and snippets.

@evanca
Created March 13, 2022 15:10
Show Gist options
  • Save evanca/0afa0d2d4ed1766ef6490fbc4bef799f to your computer and use it in GitHub Desktop.
Save evanca/0afa0d2d4ed1766ef6490fbc4bef799f to your computer and use it in GitHub Desktop.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'highscore.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List highScores = [];
Future<void> _incrementCounter() async {
HighScore(username: "User", difficulty: 0, score: 100).save();
HighScore(username: "User", difficulty: 1, score: 250).save();
HighScore(username: "User", difficulty: 3, score: 1000).save();
setState(() {
_counter++;
});
}
getScores() async {
var prefs = await SharedPreferences.getInstance();
String? source = prefs.getString('highscores');
var maps = source != null ? jsonDecode(source) : [];
setState(() {
highScores = maps.map((e) => HighScore.fromMap(e)).toList();
});
}
@override
Widget build(BuildContext context) {
getScores();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
for (var highScore in highScores)
Text(
"Difficulty: ${highScore.difficulty.toString()}, score: ${highScore.score.toString()}")
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment