Read an online text file and put it into a variable - flutter

I want to check an online txt file for the newest version code and show a dialog which says "Please update" or something similar. Is it posiible to put the content of the file into a variable?
EDIT: I tried Arpit Awasthi's solution but I get these errors:
lib/main.dart:685:25: Error: Method not found: 'HttpClient'.
var request = await HttpClient().getUrl(Uri.parse(url));
^^^^^^^^^^
lib/main.dart:687:23: Error: Method not found: 'consolidateHttpClientResponseBytes'.
var bytes = await consolidateHttpClientResponseBytes(response);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
lib/main.dart:688:5: Error: 'Directory' isn't a type.
Directory appDocDir = await getApplicationDocumentsDirectory();
^^^^^^^^^
lib/main.dart:690:5: Error: 'File' isn't a type.
File file = File("${appDocDir.path}/$fileName");
^^^^
lib/main.dart:690:17: Error: Method not found: 'File'.
File file = File("${appDocDir.path}/$fileName");
^^^^
lib/main.dart:691:5: Error: 'File' isn't a type.
File urlFile = await file.writeAsBytes(bytes);
^^^^

You can use the following function to download the file and then get the File object of that file.
static downloadFile(String url) async{
var request = await HttpClient().getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
Directory appDocDir = await getApplicationDocumentsDirectory();
String fileName = ('yourFileName.fileExtention');
File file = File("${appDocDir.path}/$fileName");
File urlFile = await file.writeAsBytes(bytes);
return urlFile;
}
Note :- I've used this plugin to get app folder path :- path_provider: ^1.6.18

Basically, what you can do is the following.
You May Define in a variable (context probably) you Current Version...
The you a async http request, you can call to an API where you check your latest release and if it is > that current one, trigger an alert dialog that shows that There is a new version available.

Related

Take a photo and saving the photo to storage fails

I am using the camera plugin to take a picture like this:
image = await cameraController.takePicture()
It is working great and I can display this image in a preview. Now I want to store the picture to the device, and I am trying this:
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String appDocumentsPath = appDocumentsDirectory.path;
String filePath = '$appDocumentsPath/images/${image!.name}';
await File(image!.path).copy(filePath);
Then I get this error:
Unhandled Exception: FileSystemException: Cannot copy file to '/data/user/0/dk.hempelfonden.frontier/app_flutter/images/CAP8310428751941012175.jpg', path = '/data/user/0/dk.hempelfonden.frontier/cache/CAP8310428751941012175.jpg' (OS Error: No such file or directory, errno = 2)
What am I missing here?
Thank you
Søren
path is the directory /data/user/0/dk.some.app/cache/CAP7304644252296628120.jpg. Try adding a /filename.jpg or .png to it.
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String appDocumentsPath = appDocumentsDirectory.path;
String filePath = '$appDocumentsPath/images/$name.png';
logDebug('Saving from: ${_image!.path}');
logDebug('Copy to: $filePath');
return await File(_image!.path).copy(filePath+".jpg");
I think you trying to copy .png file to .jgp path that is why you are facing
FileSystemException try same image type for both image paths.
I was trying to copy the image file to a directory that was not existing, added this code:
String dirPath = '$appDocumentsPath/images';
await Directory(dirPath).create(recursive: true);
you have not created the file. so thats why its show you error
File newFile = File(await filePath);
if (newFile.existsSync()) {
await newFile.delete(); // Delete File first
}
newFile.createSync(recursive: true); // Create Again

How to overwrite files in google drive using API flutter

The Problem
I'm using Google Drive to store application-specific data. I can read and write data to my drive buy whenever I want to update the config in the drive a new file is created instead of updating the old one.
I have tried the following:
Gave the file an ID but the following error appears
Unhandled Exception: DetailedApiRequestError(status: 400, message: The provided file ID is not usable.)
Got the ID generated by the API and used the same code and got the following error
Unhandled Exception: DetailedApiRequestError(status: 409, message: A file already exists with the provided ID.)
My Code:
final signIn.GoogleSignInAccount account = await _googleSignIn.signIn();
final authHeaders = await account.authHeaders;
final authenticateClient = GoogleAuthClient(authHeaders);
final driveApi = drive.DriveApi(authenticateClient);
File _data = await _report.backupData(); //gets data to be overwriten
final Stream<List<int>> mediaStream = _data.openRead();
var media = new drive.Media(mediaStream, _data.lengthSync());
var driveFile = new drive.File();
driveFile.parents=['appDataFolder'];
driveFile.name = "backup.mw";
final result = await driveApi.files.create(driveFile, uploadMedia: media,);
print("Upload result: ${result.id}");
The code you are using does a files.create file create will create a new file every time it is run.
final result = await driveApi.files.create(driveFile, uploadMedia: media,);
If you want to update an existing file then you will need to do Files.update

flutter Using flutter csv package with rootBundle

I am trying to load a csv file from assets folder which is set correctly in YAML file using csv package, but i am getting this error.
The argument type 'Future' can't be assigned to the parameter
type 'String?'.dartargument_type_not_assignable The instance member
'csvFile' can't be accessed in an initializer. Try replacing the
reference to the instance member with a different expression
I am aware that CsvToListConverter takes a string as an argument instead of Future<String>.
final csvFile = rootBundle.loadString('assets/csv_file.txt');
final csvToLIst = CsvToListConverter(eol: '\n\r', fieldDelimiter: '\t')
.convert(csvFile);
I was able read the csv file with File from dart:io. But when I build the app It kinda looses the relative path to the csv file. That's the whole point to use rootBundle I guess.
AssetBundle#loadString returns a Future<String>, so you must await it:
final csvFile = await rootBundle.loadString('assets/csv_file.txt');
final csvToLIst = CsvToListConverter(eol: '\n\r', fieldDelimiter: '\t').convert(csvFile);
Note that await must only be called in an async environment. You can read more here.
rootBundle.loadString returns a Future, so you must await it:
you should wrap your function with async first and add await in the future returning method
getWorkDone() async{
final csvFile = await rootBundle.loadString('assets/csv_file.txt');
final csvToLIst = CsvToListConverter(eol: '\n\r', fieldDelimiter: '\t')
.convert(csvFile);
}

Flutter create a file and write its contents

I am working on an app which gathers text content from server and as the next step I am trying to save them into separate files to be saved with in apps storage. Storage is a folder called 'storage'. Inside storage, there is a 'fileList.txt' file which contains the list of files.
In pubspec.yaml I declared this folder in the assets as follows:
assets:
- storage/
And I can read it using the following function:
Future<String> readFileContent() async {
String response;
response =
await rootBundle.loadString('storage/fileList.txt');
return response;
}
To save the file I made use of online examples which use 'path_provider' package. However when I try to save one of the downloaded files for instance 'file4.dat' using the following functions, I encounter the following error. How can I resolve that problem?
saveFileLocally() async {
await _writeFile();
}
Future<Null> _writeFile() async {
await (await _getLocalFile()).writeAsString(vars.fileContents);
}
Future<File> _getLocalFile() async {
// get the path to the document directory.
String dir = (await PathProvider.getApplicationSupportDirectory()).path;
print('DIR :::: ' + dir);
return new File(
'$dir/storage/files/file' + vars.newFileID.toString() + '.dat');
}
The error is:
Unhandled Exception: FileSystemException: Cannot open file,
path = '/data/user/0/com.example.ferenova_flutter_app/files/storage/file4.dat'
(OS Error: No such file or directory, errno = 2)
Thanks guys and take care !!! :)
While checking out path_provider examples, I ran into this important detail:
Directory directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory(); //FOR iOS
This solved my problem. I am no longer using default rootBundle asset to process any external files.
I think you should check your paths.
storage/fileList.txt is not the same as $dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'
you should try:
response =
await rootBundle.loadString('$dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'');
Or something similar.
GL

I have issues with the path on the getApplicationDocumentsDirectory() function

I get an error message over the path provider that says
error: The getter 'path' isn't defined for the class 'Future'.
I am trying to generate a PDF file following the https://pub.dev/packages/pdf#-example-tab- and this example https://github.com/javico2609/flutter-challenges/blob/master/lib/pages/code_examples/pdf_and_csv/pdf.dart
But as I go on I get the error that path isn't defined on the Future. But as I see on the web I am doing it right. Here is the code:
final String dir = (getApplicationDocumentsDirectory()).path;
final String path = '$dir/receta.pdf';
final File file = File(path);
file.writeAsBytesSync(newpdf.save());
As I said. I can't run the app because I get the message error: The getter 'path' isn't defined for the class 'Future'.
Also tried to write
final Future<Directory> directory = getApplicationDocumentsDirectory();
final String dir = directory.path;
final String path = '$dir/receta.pdf';
final File file = File(path);
file.writeAsBytesSync(newpdf.save());
But it doesn't work, path on the variable dir shows the error
In final Future<Directory> directory = getApplicationDocumentsDirectory(); getApplicationDocumentsDirectory() is any async function which means it will return the directory asynchronously , So then when you are trying to read directory.path;, directory is not initialized yet, its null.
Instead returning a future directory wait till it is initialized,
final Directory directory = await getApplicationDocumentsDirectory();
Import this.. it solves the issue
import 'package:path_provider/path_provider.dart';
You must put await keyword like this:
final directory = await getApplicationDocumentsDirectory();
final path = join(directory.path, 'db_todolist_sqflite');