97 lines
2.2 KiB
Dart
97 lines
2.2 KiB
Dart
|
import 'package:flutter/material.dart';
|
||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||
|
|
||
|
void main() {
|
||
|
runApp(MyApp());
|
||
|
}
|
||
|
|
||
|
class MyApp extends StatelessWidget {
|
||
|
@override
|
||
|
Widget build(BuildContext context) {
|
||
|
return MaterialApp(
|
||
|
title: 'Flutter Demo',
|
||
|
theme: ThemeData(
|
||
|
primarySwatch: Colors.red,
|
||
|
canvasColor: Colors.red.shade100,
|
||
|
accentColor: Colors.blueAccent,
|
||
|
),
|
||
|
home: MyHomePage(title: 'Hello World'),
|
||
|
);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class MyHomePage extends StatefulWidget {
|
||
|
MyHomePage({Key? key, required this.title}) : super(key: key);
|
||
|
|
||
|
final String title;
|
||
|
|
||
|
@override
|
||
|
_MyHomePageState createState() => _MyHomePageState();
|
||
|
}
|
||
|
|
||
|
class _MyHomePageState extends State<MyHomePage> {
|
||
|
int _counter = 0;
|
||
|
|
||
|
@override
|
||
|
void initState() {
|
||
|
getCounter();
|
||
|
super.initState();
|
||
|
}
|
||
|
|
||
|
void getCounter() async {
|
||
|
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||
|
setState(() {
|
||
|
_counter = prefs.getInt('counter') ?? 0;
|
||
|
});
|
||
|
}
|
||
|
|
||
|
void _incrementCounter() async {
|
||
|
int newCounter = _counter + 1;
|
||
|
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||
|
await prefs.setInt('counter', newCounter);
|
||
|
setState(() {
|
||
|
_counter = newCounter;
|
||
|
});
|
||
|
}
|
||
|
|
||
|
void reset() async {
|
||
|
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||
|
await prefs.setInt('counter', 0);
|
||
|
setState(() {
|
||
|
_counter = 0;
|
||
|
});
|
||
|
}
|
||
|
|
||
|
@override
|
||
|
Widget build(BuildContext context) {
|
||
|
return Scaffold(
|
||
|
appBar: AppBar(
|
||
|
title: Text(widget.title),
|
||
|
),
|
||
|
body: Center(
|
||
|
child: Column(
|
||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||
|
children: <Widget>[
|
||
|
Text(
|
||
|
'You have pushed the button this many times:',
|
||
|
),
|
||
|
Text(
|
||
|
'$_counter',
|
||
|
style: Theme.of(context).textTheme.headline4,
|
||
|
),
|
||
|
ElevatedButton(
|
||
|
onPressed: reset,
|
||
|
child: Text('Reset'),
|
||
|
),
|
||
|
],
|
||
|
),
|
||
|
),
|
||
|
floatingActionButton: FloatingActionButton(
|
||
|
onPressed: _incrementCounter,
|
||
|
tooltip: 'Increment',
|
||
|
child: Icon(Icons.add),
|
||
|
),
|
||
|
);
|
||
|
}
|
||
|
}
|