Created
October 16, 2023 19:25
-
-
Save codesxt/df0725c42786a02450c3f26d92ee86e5 to your computer and use it in GitHub Desktop.
Counter example with file storage
This file contains 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:io'; | |
import 'package:flutter/material.dart'; | |
import 'package:path_provider/path_provider.dart'; | |
class Home extends StatefulWidget { | |
const Home({super.key}); | |
@override | |
State<Home> createState() => _HomeState(); | |
} | |
class _HomeState extends State<Home> { | |
int counter = 0; | |
@override | |
void initState() { | |
_initializeCounter(); | |
super.initState(); | |
} | |
/// Loads and initializes [counter] from a file called counter.txt | |
_initializeCounter() async { | |
final Directory directory = await getApplicationDocumentsDirectory(); | |
String path = directory.path; | |
File file = File('$path/counter.txt'); | |
if (await file.exists()) { | |
String contents = await file.readAsString(); | |
counter = int.parse(contents); | |
setState(() {}); | |
} | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Ejemplo de Storage'), | |
backgroundColor: Theme.of(context).colorScheme.inversePrimary, | |
), | |
body: Center( | |
child: Text( | |
'$counter', | |
style: Theme.of(context).textTheme.displayLarge, | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () async { | |
counter++; | |
setState(() {}); | |
/// Stores current [counter] value in a file called counter.txt | |
final Directory directory = await getApplicationDocumentsDirectory(); | |
String path = directory.path; | |
File file = File('$path/counter.txt'); | |
file.writeAsString('$counter'); | |
}, | |
child: const Icon(Icons.circle_rounded), | |
), | |
); | |
} | |
} |
Author
codesxt
commented
Oct 16, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment