Get name of test-file inside of flutter test - flutter

Assume I have a flutter test file foo_test.dart with:
void main() {
final file = ...how to get the path of this file... 'foo_test.dart';
...
}
How can I achieve that?

The following snippet allows to retrieve the file containing main():
final mainFile = Uri.parse(RegExp(r'#.*main \((.*):.*:.*\)')
.firstMatch(StackTrace.current.toString())
.group(1))
.toFilePath();

Related

Flutter how to remove file extension when i need to put file name into variable

I use p.basename from flutter path library to get file name, but i got it with extension, how to remove extension? also to get path I use getApplicationDocumentsDerectory from path_provider library
File newFile = File(filepath);
String name = p.basename(newFile.path);
this is code I use to get file name
You just use 'basenameWithoutExtension' method like basename.
File newFile = File(filepath);
String name = p.basename(newFile.path);
String nameWithoutExtension = p.basenameWithoutExtension(newFile.path);

Converting file path to file in Flutter

I am getting the path of an image from the device storage, like this:
path = res[0]?.path;
print("path:"+path);
The output of that print is:
/data/user/0/qplan/cache/image_picker_b432f88b-3146-4a99-9e8b-acbefd066e3a2471538209034937554.jpeg
I need to convert it to File in order to upload the image to Firestore Storage.
You can get file inserting your path to File object as below;
File fileToUpload = new File(path);
You can use this.
import 'dart:async';
import 'dart:io';
path = res[0]?.path;
File(path).readAsString().then((String contents) {
print(contents);
});

Can flutter do scanning directories (recursive)?

I need to scan my assets directory for other files and directories, like
-assets
-category1
-file.1
-category2
-file.1
-file.2
Is it possible at all using Flutter, Dart? Can't find any guide to scan directories.
import 'dart:io';
void main(List<String> args) async {
FileSystemEntity entity = Directory.current;
if (args.isNotEmpty) {
//if you pass the/path/you/wish
//this block will be handled
String arg = args.first;
entityForAbsolutePath = FileSystemEntity.isDirectorySync(arg) ? Directory(arg) : File(arg);
}
var dir = Directory(entityForAbsolutePath.absolute.path);
Stream<File> scannedFiles = scanningFilesWithAsyncRecursive(dir);
scannedFiles.listen((File file) {
print(file.path);
});
}
//async* + yield* for recursive functions
Stream<File> scanningFilesWithAsyncRecursive(Directory dir) async* {
//dirList is FileSystemEntity list for every directories/subdirectories
//entities in this list might be file, directory or link
var dirList = dir.list();
await for (final FileSystemEntity entity in dirList) {
if (entity is File) {
yield entity;
} else if (entity is Directory){
yield* scanningFilesWithAsyncRecursive(Directory(entity.path));
}
}
}
You can benefit from this idea.
if you run this snippet as entry point, like this:
$ dart your_dart_project/bin/main.dart /home/uname/any/absolute/path/you/wish
it will take the/any/path/you/wish as root and travers all of subdirectories and prints every file name as absolute path like:
home/uname/any/absolute/path/you/wish/myfile.any
home/uname/any/absolute/path/you/wish/myfile1.any
home/uname/any/absolute/path/you/wish/subdir/mysubdirfile1.any
home/uname/any/absolute/path/you/wish/subdir/mysubdirfile2.any
home/uname/any/absolute/path/you/wish/subdir/inner/myinnerfile1.any
P.S. if you will not show any path to dart command like this:
$ dart your_dart_project/bin/main.dart
it will travers in the directory your_dart_project/bin,
the line FileSystemEntity entity = Directory.current; tells about it
You can read platform files and directories if you can load "dart:io" (everything but flutter web). This doesn't work for the assets. The rootBundle can give you a json string added during the build which lists the assets and fonts (AssetManifest.json and FontManifest.json), but otherwise, there are really no "directories" in the asset bundle, just assets accessible using a path-like syntax.

Import list from separate file during runtime

Problem Explanation
I have a file that looks like this:
myfile1.txt
[
{
"question": "Thanks for the help",
"answer choices": [
"Hi",
"stack",
"over",
"flow",
],
},
...
]
This file contains data that needs to be set to a variable in a separate Dart file. The file type of this data does not matter, so if a .dart file would be easier to work with that would be perfectly fine.
Example of dart file that calls for the above file:
main.dart
void main() {
List<Map<String, dynamic>> data;
for (int i=0; i<5; i++) {
data = getFile("myfile$i.txt");
// Does stuff here
}
}
Note: getFile() does not actually have to be used. It's just a placeholder for the example.
Question: How would I set the data in this file to the variable data while in a function (like main()).
My attempt
Ideally, I wouldn't want to make many changes to the data file but here is what I did:
myfile1.dart
List<Map<String, dynamic>> data = [
...
]
I changed the file type to a .dart file and created a variable that would be set to the data.
I then modified my main.dart file like so:
main.dart
void main() {
for (int i=0; i<5; i++) {
import "myfile$i.dart";
// Does stuff here
}
}
This approach fails because import cannot be called from inside a function.
You can't use the word import there. It's reserved word, used for loading flutter/dart packages, class files, etc. It's not for "loading" some arbitrary data from a file.
Flutter official website has a cookbook example for reading and writing data from and to files. Perhaps their example would work for you?
This isn't JavaScript. Before any of the program is running, all the potential Dart code must have already been compiled. You don't get to keep compiling Dart into anything after the first step of main() is active.

File cant be assigned with ImagePicker Flutter

i am learning imagepicker from https://pub.dev/packages/image_picker ,
but i don't why i got an error when i have use the way step by step.
this is the problem :
first, i declare a File variable
File _imageFile ;
then i use it in a method,
_getimg() async{
var _img = await ImagePicker(source: ImageSource.gallery);
setState(() {
_imageFile = _img ;
});
}
and then i got this error :
A value of type 'File (where File is defined in
D:\Flutter\flutter\bin\cache\pkg\sky_engine\lib\io\file.dart)' can't
be assigned to a variable of type 'File (where File is defined in
D:\Flutter\flutter\bin\cache\pkg\sky_engine\lib\html\html_dart2js.dart)'.
There is a conflict between Files declaration. The html package has one declaration of a class File and the io package has another declaration (same name, different origin).
In fact, using html is for web and io is used for console, server or mobile apps, so check your imports and delete io or html depending in the type of project you are working on.
Another solution is to define your imports like this:
import 'package:html/html.dart' as h; //"h" can change, is just an example
import 'dart:io' as i; //"i" also can be another char or word, is just an example
//And when you need to create a File,
//you can decide if you want to create
//an io File or an html File
main(){
i.File f1 = ...; //The io File, starting with "i."
h.File f2 = ...; //The html File, starting with "h."
}