📜  Flutter – 从存储中挑选并打开文件

📅  最后修改于: 2022-05-13 01:55:22.289000             🧑  作者: Mango

Flutter – 从存储中挑选并打开文件

有时在应用程序中,我们需要从手机的存储中选择并打开一个文件,在本文中,我们将使用 file_picker 和 open_fileflutter包实现相同的功能。

1.创建一个应用程序:

通过在终端上运行以下命令来创建一个新的flutter应用程序:

flutter create your_app_name

现在在 Android-Studio 或 VS-Code 等任何 IDE 中打开您的flutter项目。

2. 创建一个基本的 UI:

现在从lib/main 中删除所有样板代码。dart并为您的 UI 添加代码。为了演示,我有一个居中的材质按钮。

Dart
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
    
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.green[100],
        body: Center(
          child: MaterialButton(
            onPressed: () {},
            child: Text(
              'Pick and open file',
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.green,
          ),
        ),
      ),
    );
  }
}


Dart
import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';


Dart
void _pickFile() async {
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: false);
  
    // if no file is picked
    if (result == null) return;
  
    // we will log the name, size and path of the
    // first picked file (if multiple are selected)
    print(result.files.first.name);
    print(result.files.first.size);
    print(result.files.first.path);
  }


Dart
import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  void _pickFile() async {
      
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: false);
  
    // if no file is picked
    if (result == null) return;
  
    // we will log the name, size and path of the
    // first picked file (if multiple are selected)
    print(result.files.first.name);
    print(result.files.first.size);
    print(result.files.first.path);
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.green[100],
        body: Center(
          child: MaterialButton(
            onPressed: () {
              _pickFile();
            },
            child: Text(
              'Pick and open file',
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.green,
          ),
        ),
      ),
    );
  }
}


Dart
void _openFile(PlatformFile file) {
    OpenFile.open(file.path);
  }


Dart
void _pickFile() async {
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: true);
  
    // if no file is picked
    if (result == null) return;
  
    // we get the file from result object
    final file = result.files.first;
  
    _openFile(file);
  }


Dart
import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  void _pickFile() async {
      
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: true);
  
    // if no file is picked
    if (result == null) return;
  
    // we get the file from result object
    final file = result.files.first;
  
    _openFile(file);
  }
  
  void _openFile(PlatformFile file) {
    OpenFile.open(file.path);
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.green[100],
        body: Center(
          child: MaterialButton(
            onPressed: () {
              _pickFile();
            },
            child: Text(
              'Pick and open file',
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.green,
          ),
        ),
      ),
    );
  }
}


输出:

3. 现在添加包:

在终端中运行以下命令以添加 file_picker 包:

flutter pub add file_picker

并添加 open_file 包运行以下命令:

flutter pub add open_file

4. 导入包:

要使用file_pickeropen_file包,请通过在lib/main.xml 中添加以下行来导入它们。dart

Dart

import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';

5. 创建一个从存储中挑选文件的函数:

Dart

void _pickFile() async {
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: false);
  
    // if no file is picked
    if (result == null) return;
  
    // we will log the name, size and path of the
    // first picked file (if multiple are selected)
    print(result.files.first.name);
    print(result.files.first.size);
    print(result.files.first.path);
  }

_pickFile函数中,我们使用pick_files包中的FilePicker对象来选择文件,然后我们等待,然后将返回的FilePickerResult类型数据保存到结果变量中,如果没有选择文件,则结果变量被分配一个 null价值。您还可以根据您要选择单个文件还是多个文件来切换allowMultiple true 或false。之后,如果结果为 null 或没有选择文件,我们将终止函数。如果选择了文件,我们只需记录第一个文件的名称大小路径

然后为了让事情顺利进行,我们在材质按钮的onPressed回调中调用_pickFIle函数。毕竟我们的lib/main.dart看起来像这样:

Dart

import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  void _pickFile() async {
      
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: false);
  
    // if no file is picked
    if (result == null) return;
  
    // we will log the name, size and path of the
    // first picked file (if multiple are selected)
    print(result.files.first.name);
    print(result.files.first.size);
    print(result.files.first.path);
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.green[100],
        body: Center(
          child: MaterialButton(
            onPressed: () {
              _pickFile();
            },
            child: Text(
              'Pick and open file',
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.green,
          ),
        ),
      ),
    );
  }
}

输出:

6. 创建一个函数来打开拾取的文件:

现在,既然我们有了从存储中挑选文件的功能,让我们继续在本机应用程序中打开挑选的文件。为此,我们创建了一个名为_openFile的函数,该函数接受一个PlatformFile类型参数并打开该文件:

Dart

void _openFile(PlatformFile file) {
    OpenFile.open(file.path);
  }

现在在_pickFile函数中而不是记录选择的文件名,让我们调用_openFile函数并将结果对象中的第一个文件传递给它。

Dart

void _pickFile() async {
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: true);
  
    // if no file is picked
    if (result == null) return;
  
    // we get the file from result object
    final file = result.files.first;
  
    _openFile(file);
  }

现在毕竟这是我们的lib/main。dart看起来像这样:

Dart

import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  void _pickFile() async {
      
    // opens storage to pick files and the picked file or files
    // are assigned into result and if no file is chosen result is null.
    // you can also toggle "allowMultiple" true or false depending on your need
    final result = await FilePicker.platform.pickFiles(allowMultiple: true);
  
    // if no file is picked
    if (result == null) return;
  
    // we get the file from result object
    final file = result.files.first;
  
    _openFile(file);
  }
  
  void _openFile(PlatformFile file) {
    OpenFile.open(file.path);
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.green[100],
        body: Center(
          child: MaterialButton(
            onPressed: () {
              _pickFile();
            },
            child: Text(
              'Pick and open file',
              style: TextStyle(color: Colors.white),
            ),
            color: Colors.green,
          ),
        ),
      ),
    );
  }
}

输出: