Flutter: как удалить файл из каталога приложения Flutter - PullRequest
0 голосов
/ 09 февраля 2020

Я хочу удалить текстовый файл (содержащий некоторые данные о пользователе) внутри каталога моего приложения для флаттера

как это сделать?

1 Ответ

0 голосов
/ 10 февраля 2020

Вы можете скопировать и запустить полный код ниже
Вы можете использовать file.delete()
фрагмент кода

  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;
        }
      }

рабочая демонстрация

enter image description here

рабочая демонстрация перед удалением файла

enter image description here

рабочая демонстрация после удаления файла

enter image description here

полный код

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),
      ),
    );
  }
}
...