cpd_2023_hello/hello_world2/lib/main.dart

97 lines
2.2 KiB
Dart
Raw Permalink Normal View History

2023-04-04 15:29:01 +02:00
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),
),
);
}
}