In the last video we talked about how to drag files into your app, and you can click a button in your app to bring up a selection box to upload a file, which is also an essential feature.
file_selector
Install π
Click file_Selector to get the latest version. The following is the latest version at the time of writing:
file_selector: ^ 0.8.4 + 1
Copy the code
π» Note: Additional operations are required when developing macOS applications, which can be found here
Understand π§©
In the File_Selector plug-in, we need to know about the object XTypeGroup and the method openFiles.
XTypeGroup is used to create a new group with the given label and file extension, and group representations that do not provide any type options allow any type.
XTypeGroup can pass in five parameters:
String? label
: Used to distinguish themselvesList<String>? extensions
: Filters non-descriptive file suffixes. By default, all types of files are loadedList<String>? mimeTypes
: Applies to files in LinuxList<String>? macUTIs
: Applies to file types in the MAC operating systemList<String>? webWildCards
: mainly for the type of web page development
The openFile method returns an XFile object that can take three arguments:
List acceptedTypeGroups = const []
: Accepted type groups, passed in a list of XTypeGroupsString? initialDirectory
: Initializes the folder. Open the File dialog box to load the file and return to the file pathString? confirmButtonText
: Popup “Open” button display text
The openFiles method returns a list of XFile objects, passing in the same parameters as openFile.
Using π₯©
The selected file needs to be read out at last, which takes a path of type String:
String path = ' ';
Copy the code
To select an image, we need to define an XTypeGroup object:
final xType = XTypeGroup(label: 'images', extensions: ['jpg'.'png']);
Copy the code
Select a single image
Open the popover to select a single file and use the openFile method:
final XFile? file = await openFile(acceptedTypeGroups: [xType]);
Copy the code
Pass the path value of the obtained XFile object to path. Of course, not every time you open the popover you will select the image, so you need to decide:
if(file ! =null) {
path = file.path;
setState((){});
} else {
BotToast.showText(text: 'What do you do if you don't select the image to open π€');
}
Copy the code
There are two other properties in the openFile method that we can modify:
final XFile? file = await openFile(
acceptedTypeGroups: [xType],
initialDirectory: r'C:\Users\ilgnefz\Pictures',
confirmButtonText: 'Hey hey hey',);Copy the code
The initialDirectory attribute does not seem to use π. We have seen the official example and have not used this parameter, so we will ignore it in the future.
Select multiple images
To select multiple images, we need to define an array of paths:
final List<String> paths = [];
Copy the code
The XTypeGroup object is the same as before, but the important thing is to use the openFiles method:
final List<XFile> files = await openFiles(acceptedTypeGroups: [xType]);
Copy the code
Assign the obtained list of file paths to PATHS:
if(file ! =null) {
paths.addAll(files.map((e) => e.path).toList());
setState((){});
} else {
BotToast.showText(text: 'What do you do if you don't select the image to open π€');
}
Copy the code
All right, let’s see how it goes
Reading text files
To read a text file, we need to get the name and contents of the file:
final String title = ' ';
final String content = ' ';
Copy the code
Just change the XTypeGroup object again:
final XTypeGroup xType = XTypeGroup(label: 'text', extensions: ['txt']);
final XFile? file = await openFile(acceptedTypeGroups: [xType]);
Copy the code
Assign the attributes of the acquired XFile object to the object we defined:
if(file ! =null) {
title = file.name;
content = await file.readAsString();
setState((){});
} else {
BotToast.showText(text: 'Opened a lonely π');
}
Copy the code
Storing text files
The fromData method in the XFile object is used to store text. Let’s take a look at what arguments need to be passed in this method:
Uint8List bytes
: Indicates the main content of the storageString? mimeType
: Indicates the mine type of the fileString? name
: file name? The test is useless πint? length
: Do not know what length, anyway can not intercept the content πDateTime? lastModified
: Indicates the time when the file was last modifiedString? path
: File saving path? The test has no effect πCrossFileTestOverrides? overrides
: Overrides some methods of the CrossFile for testing
(If the above parameters are tested out by friends, you can inform π)
Before we can store a text file, we need to know which folder to store it in:
final String? path = await getSavePath();
Copy the code
From xfile.fromData then add the parameters needed for xfile.fromdata:
if(path ! =null) {
// Encode the content to UTf8
final Uint8List fileData = const Utf8Encoder().convert(content);
const String fileMimeType = 'text/plain';
final XFile xFile = XFile.fromData(
fileData,
mimeType: fileMimeType,
name: title,
);
await xFile.saveTo(path);
} else {
BotToast.showText(text: 'Give you a look of their own experience π');
}
Copy the code
Get folder path
To read the folder path, use the getDirectoryPath method:
final String? path = await getDirectoryPath();
if(path ! =null) {
title = 'the directory';
content = path;
setState((){});
}
Copy the code
file_picker
Install π
Click file_picker to get the latest version. The following is the latest version at the time of writing:
file_picker: ^ 4.5.1
Copy the code
Using π₯©
Define a default path:
String path = ' ';
Copy the code
Select a single file
Selecting a single file requires the pickFiles method, which takes 10 arguments:
String? dialogTitle
: Popover titleString? initialDirectory
: Initialization folderFileType type = FileType.any
: Indicates the type of the fileList<String>? allowedExtensions
: Allowed file name suffixdynamic Function(FilePickerStatus)? onFileLoading
: Listens for the status of file selectionbool allowCompression = true
: Indicates whether compression is allowedbool allowMultiple = false
: Indicates whether multiple files can be selectedbool withData = false
: If true, the selected file will immediately serve up its byte data in memory in the form of a Uint8List, which is useful if you select it for server uploads or similar operations. However, keep in mind that enabling this feature on IO (iOS and Android) can cause out-of-memory issues if you allow multiple selections or select large files. Use [withReadStream] instead. On the Web, the default istrue
, the other forfalse
bool withReadStream = false
: The picked file will provide its byte data in the form of [Stream<List>], which is useful for uploading and processing large filesbool lockParentWindow = false
Whether to keep a subwindow (file selector window) in front of a Flutter window until it closes (e.g., a modal window). This parameter applies only to Windows
FilePickerResult? result = await FilePicker.platform.pickFiles();
if(result ! =null) { File file = File(result.files.single.path!) ; path = file.path; setState((){}); }Copy the code
Let’s try adding some parameters:
FilePickerResult? result = await FilePicker.platform.pickFiles(
dialogTitle: 'My place is mine',
initialDirectory: r'C:\Users\ilgnefz\Pictures\Saved Pictures',
type: FileType.image,
);
Copy the code
InitialDirectory did not work π
Select multiple files
Define an array that accepts all paths:
final List<String> paths = [];
Copy the code
FilePickerResult? result = await FilePicker.platform.pickFiles(
allowMultiple: true,);if(result ! =null) { paths = result.files.map((e) => e.path!) .toList(); setState((){}); }Copy the code
Reading file Information
Using the above method, we get a PlatformFile object:
FilePickerResult? result = await FilePicker.platform.pickFiles();
PlatformFile file = result.files.single;
Copy the code
This object has the following properties:
name
: File namesize
: File size, in bytesbytes
: Bytes of data for this file. This is especially useful if you want to manipulate its data or easily upload it elsewhere.See here in the FAQAn example of how to use it to upload on the web.extension
: File suffixpath
: File pathidentifier
: Platform identifier of the original file, which is on AndroidUriAnd on the iOSNSURL. The other is nullreadStream
: Converts the file contents into streams for reading
Storing files
The saveFile method is used to store the file, which takes 6 arguments:
String? dialogTitle
: same as the pickFiles methodString? fileName
: The name of the file to be storedString? initialDirectory
: same as the pickFiles methodFileType type = FileType.any
: same as the pickFiles methodList ? allowedExtensions
: same as the pickFiles methodbool lockParentWindow = false
: same as the pickFiles method
String? outputFile = await FilePicker.platform.saveFile();
Copy the code
(it’s even… This method doesn’t even have parameters to save content. Just play π. Officials say the method is moot.
Get folder path
To get the folder, use the getDirectoryPath method, passing in three parameters:
String? dialogTitle
: same as the pickFiles methodbool lockParentWindow = false
: same as the pickFiles methodString? initialDirectory
: same as the pickFiles method
final String title = ' ';
final String content = ' ';
Copy the code
String? dir = await FilePicker.platform.getDirectoryPath();
if(path ! =null) {
title = 'the directory';
content = path;
setState((){});
}
Copy the code
π«OK, that’s the end of this article, which is for the current version of the plug-in and is not guaranteed to be applicable to future iterations of plug-in usage.
Finally, thanks to the flutter team and miguelpruivo for the development and maintenance of the above plugin π. This application code has been uploaded to Github and Gitee, there is a need to download down to view learning.