Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: how to delete a file inside the Flutter app directory

I want to delete a text file (which hold some data about the user) inside the directory of my flutter app

how to do so?

like image 608
Karrar Avatar asked Feb 09 '20 14:02

Karrar


People also ask

How do you delete files from local storage?

setItem() : Add key and value to localStorage. getItem() : This is how you get items from localStorage. removeItem() : Remove an item by key from localStorage. clear() : Clear all localStorage.


1 Answers

You can copy paste run full code below
You can use file.delete()
code snippet

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    print('path ${path}');
    return File('$path/counter.txt');
  }

  Future<int> deleteFile() async {
        try {
          final file = await _localFile;

          await file.delete();
        } catch (e) {
          return 0;
        }
      }

working demo

enter image description here

working demo before delete file

enter image description here

working demo after delete file

enter image description here

full code

import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(
    MaterialApp(
      title: 'Reading and Writing Files',
      home: FlutterDemo(storage: CounterStorage()),
    ),
  );
}

class CounterStorage {
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    print('path ${path}');
    return File('$path/counter.txt');
  }

  Future<int> deleteFile() async {
    try {
      final file = await _localFile;

      await file.delete();
    } catch (e) {
      return 0;
    }
  }

  Future<int> readCounter() async {
    try {
      final file = await _localFile;

      // Read the file
      String contents = await file.readAsString();

      return int.parse(contents);
    } catch (e) {
      // If encountering an error, return 0
      return 0;
    }
  }

  Future<File> writeCounter(int counter) async {
    final file = await _localFile;

    // Write the file
    return file.writeAsString('$counter');
  }
}

class FlutterDemo extends StatefulWidget {
  final CounterStorage storage;

  FlutterDemo({Key key, @required this.storage}) : super(key: key);

  @override
  _FlutterDemoState createState() => _FlutterDemoState();
}

class _FlutterDemoState extends State<FlutterDemo> {
  int _counter;

  @override
  void initState() {
    super.initState();
    widget.storage.readCounter().then((int value) {
      setState(() {
        _counter = value;
      });
    });
  }

  Future<File> _incrementCounter() {
    setState(() {
      _counter++;
    });

    // Write the variable as a string to the file.
    return widget.storage.writeCounter(_counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Reading and Writing Files')),
      body: Column(
        children: <Widget>[
          Center(
            child: Text(
              'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
            ),
          ),
          RaisedButton(
            onPressed: () {
              widget.storage.deleteFile();
            },
            child: Text("delete file"),
            textColor: Color(0xffff0000),
            color: Color(0xff11f1f1),
            highlightColor: Color(0xff00ff00),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
like image 167
chunhunghan Avatar answered Oct 04 '22 21:10

chunhunghan