如何从Flutter的内部和外部存储中获取所有PDF文件? [英] How to get all PDF files from internal as well as external storage in Flutter?

查看:660
本文介绍了如何从Flutter的内部和外部存储中获取所有PDF文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示内部和外部存储中存在的所有pdf文件,因此在点击该特定文件时,我想在全屏对话框中打开该文件。

解决方案

因此,您需要执行以下操作:




  • 授予对您的PDF文件所在目录中的外部存储的访问权限。我们将该文件夹称为<外部存储设备> / pdf

  • 列出该目录的所有文件并显示给用户。 / li>
  • 使用可以可视化PDF的应用程序打开所选文件。



认为我建议您使用那些flutter软件包:








  • 您有很多东西要学习。我希望这对您来说是一个有用的游乐场。



    这是用于外部存储的,但是您还可以获取Internal and Temporary目录,其行为与此类似。

    p>

    如果要在iOS上执行相同的操作,则需要在iOS项目上也创建相同的本机代码 pdfViewer 。始终参考 flutter平台频道进行操作。请记住,iOS设备上不存在外部存储。因此,您只能使用应用程序沙箱文档文件夹或临时文件夹。



    GitHub存储库



    快乐编码。


    I want to show All pdf files present in internal as well as external storage, So on tapping that particular file, i want to open that file in full screen dialog.

    解决方案

    So in order to do that you need to:

    • Grant access to external storage in a directory where there are your PDF file. Let's call that folder <external storage>/pdf.
    • List all file of that directory a display them to the user.
    • Open the selected file with an application that can visualize PDF.

    In order to do all that thinks I suggest you to use those flutter packages:

    With path_provider you can get the external storage directory of an Android device.

    Directory extDir = await getExternalStorageDirectory();
    String pdfPath = extDir + "/pdf/";
    

    In order to access external storage you need to set this permission request in the ApplicationManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    You could also only use READ_EXTERNAL_STORAGE but then the simple_permission plugin won't work.

    With the simple_permission plugin then you go and ask user to be granted external storage access:

      bool externalStoragePermissionOkay = false;
    
      _checkPermissions() async {
        if (Platform.isAndroid) {
          SimplePermissions
              .checkPermission(Permission.WriteExternalStorage)
              .then((checkOkay) {
            if (!checkOkay) {
              SimplePermissions
                  .requestPermission(Permission.WriteExternalStorage)
                  .then((okDone) {
                if (okDone) {
                  debugPrint("${okDone}");
                  setState(() {
                    externalStoragePermissionOkay = okDone;
                    debugPrint('Refresh UI');
                  });
                }
              });
            } else {
              setState(() {
                externalStoragePermissionOkay = checkOkay;
              });
            }
          });
        }
      }
    

    Once we have been granted external storage access we an list our PDF directory:

    List<FileSystemEntity> _files;
    _files = dir.listSync(recursive: true, followLinks: false);
    

    And show them in a ListView:

    return new ListView.builder(
          padding: const EdgeInsets.all(16.0),
          itemCount: _files.length,
          itemBuilder: (context, i) {
            return _buildRow(_files.elementAt(i).path);
          });
    

    Than you have to open them with a viewer when the user tap on them.

    To do that there isn't an easy way, because with Android we need to build a ContentUri and give access to this URI to the exteranl application viewer.

    So we do that in Android and we use flutter platform channels to call the Android native code.

    Dart:

    static const platform =
          const MethodChannel('it.versionestabile.flutterapp000001/pdfViewer');
    var args = {'url': fileName};
              platform.invokeMethod('viewPdf', args);
    

    Native Java Code:

    public class MainActivity extends FlutterActivity {
      private static final String CHANNEL = "it.versionestabile.flutterapp000001/pdfViewer";
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
    
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                new MethodChannel.MethodCallHandler() {
                  @Override
                  public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                    if (call.method.equals("viewPdf")) {
                      if (call.hasArgument("url")) {
                        String url = call.argument("url");
                        File file = new File(url);
                        //*
                        Uri photoURI = FileProvider.getUriForFile(MainActivity.this,
                                BuildConfig.APPLICATION_ID + ".provider",
                                file);
                                //*/
                        Intent target = new Intent(Intent.ACTION_VIEW);
                        target.setDataAndType(photoURI,"application/pdf");
                        target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        startActivity(target);
                        result.success(null);
                      }
                    } else {
                      result.notImplemented();
                    }
                  }
                });
      }
    }
    

    And after all we can have our PDF list and viewable on Android.

    You have a lot to study. I hope this could be an useful playground for you.

    This is for External Storage, but you can get Also the Internal and Temporary directory and act similarly as here.

    If you wanna do the same thing on iOS you need to create the same Native Code pdfViewer also on iOS project. Refer alway to flutter platform channels in order to do it. And remember that the external storage doesn't exists on iOS devices. So you could use only the application sandbox document folder or the temporary one.

    GitHub repo.

    Happy coding.

    这篇关于如何从Flutter的内部和外部存储中获取所有PDF文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆