Skip to content

Instantly share code, notes, and snippets.

@codesxt
Created October 16, 2023 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codesxt/df0725c42786a02450c3f26d92ee86e5 to your computer and use it in GitHub Desktop.
Save codesxt/df0725c42786a02450c3f26d92ee86e5 to your computer and use it in GitHub Desktop.
Counter example with file storage
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),
),
);
}
}
@codesxt
Copy link
Author

codesxt commented Oct 16, 2023

Screenshot_1697484048

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment