How to Delete cache and app dir in flutter - flutter

In my flutter app, I store some images in cache directory and some files in application document directory, now I want to add possibility to my users to delete the cache dir and app dir,
How can I achieve this?

You need path_provider package
Then try this code:
Future<void> _deleteCacheDir() async {
final cacheDir = await getTemporaryDirectory();
if (cacheDir.existsSync()) {
cacheDir.deleteSync(recursive: true);
}
}
Future<void> _deleteAppDir() async {
final appDir = await getApplicationSupportDirectory();
if(appDir.existsSync()){
appDir.deleteSync(recursive: true);
}
}

This code may help you :
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;
return File('$path/counter.txt');
}
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: Center(
child: Text(
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Also, you can find very helpful document here:
https://github.com/flutter/samples/blob/master/INDEX.md

Related

final imageFile = await File(path); doesn't create a file

I am using the camera to take a picture and save the picture on phones memory to later send it to AWS. I can take a picture and the path for the picture is there, but I am failing to create a file from the path using:
final imageFile = await File(path);
Why is the file not being created here? I always get 'Image file does not exist' on debug console.
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class CameraPage extends StatefulWidget {
// 1
final CameraDescription? camera;
// 2
final ValueChanged? didProvideImagePath;
CameraPage({Key? key, this.camera, this.didProvideImagePath})
: super(key: key);
#override
State<StatefulWidget> createState() => _CameraPageState();
}
class _CameraPageState extends State<CameraPage> {
CameraController? _controller;
Future<void>? _initializeControllerFuture;
#override
void initState() {
super.initState();
// 3
_controller = CameraController(widget.camera!, ResolutionPreset.medium);
_initializeControllerFuture = _controller?.initialize();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<void>(
future: _initializeControllerFuture,
builder: (context, snapshot) {
// 4
if (snapshot.connectionState == ConnectionState.done) {
return CameraPreview(this._controller!);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
// 5
floatingActionButton: FloatingActionButton(
child: Icon(Icons.camera), onPressed: _takePicture),
);
}
// 6
void _takePicture() async {
try {
await _initializeControllerFuture;
final tmpDirectory = await getTemporaryDirectory();
final filePath = '${DateTime.now().millisecondsSinceEpoch}.jpg';
final path = join(tmpDirectory.path, filePath);
await _controller?.takePicture();
widget.didProvideImagePath!(path);
final imageFile = await File(path);
if (imageFile.existsSync())
print('Image file exists');
else
print('Image file does not exist');
} catch (e) {
print(e);
}
}
// 7
#override
void dispose() {
_controller?.dispose();
super.dispose();
}
}
takePicture method will return taken image as XFile, you can use the XFile path to create a File with taken Image path like below code.
File? imageFile;
XFile? xFile = await _controller?.takePicture();
if (xFile != null) {
imageFile = File(xFile.path);
}
if (imageFile != null && imageFile.existsSync()) {
print('Image file exists');
} else {
print('Image file does not exist');
}

How to read file from file to flutter?

I have code that I use to write data to a file (such as global settings for an application). I write down the data and see. But the problem is that I do not understand how to take these mini data from another page. For example I wrote the word "Test" and I want and I want to assign that word to some variable in another page. I will be grateful for your help. Here is my code:
import 'dart:io';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Reading and Writing to Storage",
home: Home(
storage: Storage(),
),
);
}
}
class Home extends StatefulWidget {
final Storage storage;
Home({Key key, #required this.storage}) : super(key: key);
#override
HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
TextEditingController controller = TextEditingController();
String state;
Future<Directory> _appDocDir;
#override
void initState() {
super.initState();
widget.storage.readData().then((String value) {
setState(() {
state = value;
});
});
}
Future<File> writeData() async {
setState(() {
state = controller.text;
controller.text = '';
});
return widget.storage.writeData(state);
}
void getAppDirectory() {
setState(() {
_appDocDir = getApplicationDocumentsDirectory();
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Reading and Writing Files'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text('${state ?? "File is Empty"}'),
TextField(
controller: controller,
),
RaisedButton(
onPressed: writeData,
child: Text('Write to File'),
),
RaisedButton(
child: Text("Get DIR path"),
onPressed: getAppDirectory,
),
FutureBuilder<Directory>(
future: _appDocDir,
builder:
(BuildContext context, AsyncSnapshot<Directory> snapshot) {
Text text = Text('');
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
text = Text('Error: ${snapshot.error}');
} else if (snapshot.hasData) {
text = Text('Path: ${snapshot.data.path}');
} else {
text = Text('Unavailable');
}
}
return new Container(
child: text,
);
},
)
],
),
),
);
}
}
class Storage {
Future<String> get localPath async {
final dir = await getApplicationDocumentsDirectory();
return dir.path;
}
Future<File> get localFile async {
final path = await localPath;
return File('$path/db.txt');
}
Future<String> readData() async {
try {
final file = await localFile;
String body = await file.readAsString();
return body;
} catch (e) {
return e.toString();
}
}
Future<File> writeData(String data) async {
final file = await localFile;
return file.writeAsString("$data");
}
}
And scrin:
You can pass the value to other page using Navigator and parameter.
class NewScreen extends StatelessWidget {
final String data;
NewScreen({this.data});
...
}
When you move to 'NewScreen' by using Navigator at your 'Home' page,
pass the data what you transfer.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewScreen(data: 'Test'),
),
);

how to load file from online in flutter

I'm able to load file from my code. But the problem is, how to load the file from online server which is from this link- https://freevpn.gg/c/59.139.187.41/udp
My current code is-
var contennt=await rootBundle.loadString('assets/vpnconfig.ovpn');
You could use flutter cache manager to download the file and then read it. https://pub.dev/packages/flutter_cache_manager
String url = 'your_link';
final file = await DefaultCacheManager().getSingleFile(url);
var content = await file.readAsString();
dependencies:
flutter_filereader: ^2.2.0
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_filereader_example/file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void initState() {
Permission.storage.request();
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String taskId;
Map<String, String> iosfiles = {
"docx": "assets/files/docx.docx", // IOS test
"doc": "assets/files/doc.doc", // IOS test
"xlsx": "assets/files/xlsx.xlsx", // IOS test
"xls": "assets/files/xls.xls", // IOS test
"pptx": "assets/files/pptx.pptx", // IOS test
"ppt": "assets/files/ppt.ppt", // IOS test
"pdf": "assets/files/pdf.pdf", // IOS test
"txt": "assets/files/txt.txt", // IOS test
"jpg": "assets/files/jpg.jpg", //
"jpeg": "assets/files/jpeg1.jpeg", //
"png": "assets/files/png.png", //
};
Map<String, String> androidfiles = {
"docx": "assets/files/docx.docx", // android test
"doc": "assets/files/doc.doc", // android test
"xlsx": "assets/files/xlsx.xlsx", // android test
"xls": "assets/files/xls.xls", // android test
"pptx": "assets/files/pptx.pptx", // android test
"ppt": "assets/files/ppt.ppt", // android test
"pdf": "assets/files/pdf.pdf", // android test
"txt": "assets/files/txt.txt" // android test
};
Map<String, String> files;
#override
void initState() {
if (Platform.isAndroid) {
files = androidfiles;
} else {
files = iosfiles;
}
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('File Reader'),
),
body: ListView.builder(
itemBuilder: (ctx, index) {
return item(files.keys.elementAt(index), files.values.elementAt(index));
},
itemCount: files.length,
),
);
}
item(String type, String path) {
return GestureDetector(
onTap: () {
onTap(type, path);
},
child: Container(
alignment: Alignment.center,
height: 50,
margin: EdgeInsetsDirectional.only(bottom: 5),
color: Colors.blue,
child: Center(
child: Text(
type,
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
),
);
}
onTap(String type, String assetPath) async {
String localPath = await fileLocalName(type, assetPath);
if (!await File(localPath).exists()) {
if (!await asset2Local(type, assetPath)) {
return;
}
}
Navigator.of(context).push(MaterialPageRoute(builder: (ctx) {
return FileReaderPage(
filePath: localPath,
);
}));
}
fileLocalName(String type, String assetPath) async {
String dic = await _localSavedDir() + "/filereader/files/";
return dic + base64.encode(utf8.encode(assetPath)) + "." + type;
}
fileExists(String type, String assetPath) async {
String fileName = await fileLocalName(type, assetPath);
if (await File(fileName).exists()) {
return true;
}
return false;
}
asset2Local(String type, String assetPath) async {
if (Platform.isAndroid) {
if (!await Permission.storage.isGranted) {
debugPrint("没有存储权限");
return false;
}
}
File file = File(await fileLocalName(type, assetPath));
if (await fileExists(type, assetPath)) {
await file.delete();
}
await file.create(recursive: true);
//await file.create();
debugPrint("文件路径->" + file.path);
ByteData bd = await rootBundle.load(assetPath);
await file.writeAsBytes(bd.buffer.asUint8List(), flush: true);
return true;
}
_localSavedDir() async {
Directory dic;
if (defaultTargetPlatform == TargetPlatform.android) {
dic = await getExternalStorageDirectory();
} else if (defaultTargetPlatform == TargetPlatform.iOS) {
dic = await getApplicationDocumentsDirectory();
}
return dic.path;
}
}

How to save and load data into/from local file?

I'm new in Flutter and I want to save data into local file and load when open screen.
Any help?
You can use path_provider package. Here is example.
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;
return File('$path/counter.txt');
}
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: Center(
child: Text(
'Button tapped $_counter time${_counter == 1 ? '' : 's'}.',
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Flutter passing variable into Widget

Hy guys i try two methods to pass variable inside widget in this case shared preferences.i can't pass _counterios or _counterdroid inside Widget build(BuildContext context) {... i try also localstorage wath's the best method and how??? thanks.. Code below
_loadCounter() async {
print("inizializzazione versione");
if (Platform.isAndroid) {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counterdroid = (prefs.getString('counterdroid'));
print(_counterdroid + "lettura file");
});
}
else if (Platform.isIOS) {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counterios = (prefs.getString('counterios'));
print(_counterios + "lettura file");
});
}
}
Widget build(BuildContext context) {
print(_counterdroid + "controllo tablet");
if (_counterdroid == "ipadpro") {
return new Scaffold(
appBar: new AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/pngapp/logobianco.png',
fit: BoxFit.contain,
height: 20,
),
Container(
padding: const EdgeInsets.all(10.0),
child: Text('La Corte TakeAway'))
],
),
),
);
}
}
ok... code is...
import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:social_share_plugin/social_share_plugin.dart';
import 'package:takeaway/pages/informazioni.dart';
import 'package:takeaway/pages/popup.dart';
import 'package:takeaway/pages/popup_content.dart';
import 'package:map_launcher/map_launcher.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:takeaway/pages/ncl.dart';
import 'dart:io' show Platform;
Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
return <String, dynamic>{
'model': build.model,
};
}
Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {
return <String, dynamic>{
'utsname.machine:': data.utsname.machine,
};
}
deviceInfo() async{
final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
Map<String, dynamic> deviceData = <String, dynamic>{};
try {
if (Platform.isAndroid) {
deviceData = _readAndroidBuildData(await deviceInfoPlugin.androidInfo);
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
final String droiddevice = androidInfo.model;
final prefsdroid = await SharedPreferences.getInstance();
prefsdroid.setString('counterdroid', droiddevice);
print(droiddevice);
} else if (Platform.isIOS) {
deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo);
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
final String iosdevice = iosInfo.utsname.machine;
final prefsios = await SharedPreferences.getInstance();
prefsios.setString('counterios', iosdevice);
}
} on PlatformException {
deviceData = <String, dynamic>{
'Error:': 'Failed to get platform version.'
};
}
}
class CallsAndMessagesService {
void call(String number) => launch("tel:$number");
void sendSms(String number) => launch("sms:$number");
void sendEmail(String email) => launch("mailto:$email");
}
final String telephoneNumber = "+393287875572";
void main() {
runApp(new MyApp());
deviceInfo();
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'La Corte TakeAway',
theme: new ThemeData(
primarySwatch: Colors.red,
primaryColor: const Color(0xFFc42e2e),
accentColor: const Color(0xFFfafafa),
canvasColor: const Color(0xFFfafafa),
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _counterios = "";
String _counterdroid = "";
#override
void initState() {
super.initState();
_loadCounter();
}
#override
Widget textSection = new Container(
padding: const EdgeInsets.all(32.0),
child: new Text(
'Informazioni',
softWrap: true,
),
);
_loadCounter() async {
print("inizializzazione versione");
if (Platform.isAndroid) {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counterdroid = (prefs.getString('counterdroid'));
print(_counterdroid+"lettura file");
});
}
else if (Platform.isIOS) {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counterios = (prefs.getString('counterios'));
print(_counterios+"lettura file");
});
}
}
Widget build ( BuildContext context ) {
print(_counterdroid+"controllo tablet"); }
All another pages attach no matter... variable _counterios and _counterdroid have value of device only not pass into widget and i need there...
I am not sure weather this solution will work or not, but you can try this.
call _loadCounter in initState.
#override
void initState() {
super.initState();
}
if this does not work, can you please share code of _MyHomePageState extends State<MyHomePage> ?
Updated after code updated.
try like this, this is working for me.
_loadCounter() async {
print("inizializzazione versione");
if (Platform.isAndroid) {
SharedPreferences prefs = await SharedPreferences.getInstance();
_counterdroid = (prefs.getString('counterdroid'));
print(_counterios);
}
else if (Platform.isIOS) {
SharedPreferences prefs = await SharedPreferences.getInstance();
_counterios = (prefs.getString('counterios'));
print(_counterios);
}
}