1 Star 0 Fork 0

TianMaGongChang/flutter_wechat_assets_picker

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

Flutter 仿微信资源选择器

pub package pub package Build status CodeFactor GitHub license

Awesome Flutter GitHub stars GitHub forks FlutterCandies

Language: English | 中文简体

对标微信的资源选择器,基于photo_manager实现资源相关功能,extended_image用于查看图片,provider用于协助管理选择器的状态。

拍照及录制视频,请查看 example 详细用法,并前往 wechat_camera_picker

目录 🗂

迁移指南 ♻️

查看 迁移指南.

特性 ✨

  • 💚 99%的微信风格
  • 📷 图片资源支持
    • 🔬HEIC格式图片支持
  • 🎥 视频资源支持
  • 🎶 音频资源支持
  • 1️⃣ 单资源模式
  • 💱 国际化支持
  • ➕ 特殊 widget 构建支持(前置/后置)
  • 🗂 自定义路径排序支持
  • 📝 自定义文本构建支持
  • ⏳ 自定义筛选规则支持( photo_manager
  • 🎏 完整的自定义主题
  • 💻 支持 MacOS

截图 📸

1 2 3
4 5 6
7 8 9

开始前的注意事项 ‼️

尽管该库提供了资源的选择,其仍然要求使用者构建自己的方法来处理显示、上传等操作。如果你在使用该库的过程对某些方法或API有疑问,请运行demo并查看photo_manager对相关方法的使用说明。

准备工作 🍭

版本限制

Flutter SDK:>=1.17.0

如果在 flutter pub get 时遇到了失败问题,请使用 dependency_overrides 解决。参考这里

Flutter

wechat_assets_picker添加至pubspec.yaml引用。

dependencies:
  wechat_assets_picker: ^latest_version

最新的稳定版本是: pub package

最新的开发版本是: pub package

在你的代码中导入:

import 'package:wechat_assets_picker/wechat_assets_picker.dart';

Android

依赖要求项目的安卓原生部分整合至 Android embedding v2,更多信息请至 Upgrading pre 1.12 Android projects 查看。

需要声明的权限:INTERNET, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, ACCESS_MEDIA_LOCATION

如果你发现有一些与Glide有关的警告日志输出,那么主项目就需要实现 AppGlideModule。请查看 Generated API.

iOS

ios/Podfile 中指定最低构建版本至 9.0

platform :ios, '9.0'

将以下内容添加至info.plist

<key>NSAppTransportSecurity</key>
<dict>
	<key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>
<key>NSPhotoLibraryUsageDescription</key>
<string>你的相册权限描述</string>

MacOS

目前 Flutter 桌面版仍然在开发阶段,所以请注意,任何与桌面版本有关的问题都不会受到技术支持。

  1. macos/Podfile 中指定最低构建版本至 10.15

  2. 使用 Xcode 打开 macos/Runner.xcworkspace。接着根据下面的截图将最低构建版本提升至 10.15

  3. step 1

  4. step 2

  5. 与 iOS 一样,添加相同的东西到 info.plist 里。

使用方法 📖

参数名 类型 描述 默认值
maxAssets int 最多选择的图片数量 9
pageSize int 分页加载时每页加载的资源数量。必须为网格数的倍数。 设置为null可以取消分页。 320 (80 * 4)
pathThumbSize int 选择器的缩略图大小 80
gridCount int 选择器网格数量 4
previewThumbSize List<int> 预览时图片的缩略图大小 null
requestType RequestType 选择器选择资源的类型 RequestType.image
specialPickerType SpecialPickerType 提供一些特殊的选择器类型以整合非常规的选择行为 null
selectedAssets List<AssetEntity> 已选的资源。确保不重复选择。如果你允许重复选择,请将其置空。 null
themeColor Color 选择器的主题色 Color(0xff00bc56)
pickerTheme ThemeData 选择器的主题提供,包括查看器 null
sortPathDelegate SortPathDeleage 资源路径的排序实现,可自定义路径排序方法 CommonSortPathDelegate
textDelegate DefaultAssetsPickerTextDelegate 选择器的文本代理构建,用于自定义文本 DefaultAssetsPickerTextDelegate()
filterOptions FilterOptionGroup 允许用户自定义资源过滤条件 null
specialItemBuilder WidgetBuilder 自定义item的构造方法 null
specialItemPosition SpecialItemPosition 允许用户在选择器中添加一个自定义item,并指定位置。 SpecialPosition.none
allowSpecialItemWhenEmpty bool 在资源为空时是否允许显示自定义item false
routeCurve Curve 选择构造路由动画的曲线 Curves.easeIn
routeDuration Duration 选择构造路由动画的时间 const Duration(milliseconds: 500)

简单的使用方法

final List<AssetEntity> assets = await AssetPicker.pickAssets(context);

或者

AssetPicker.pickAsset(context).then((List<AssetEntity> assets) {
  /.../
});

完整参数的使用方法

欲了解各种选择器模式,请直接运行 example 查看。

展示选中的资源

AssetEntityImageProvider 可以为 图片 & 视频 展示缩略图,以及展示 图片的原图。它的使用方法与常见的 ImageProvider 一致。

Image(image: AssetEntityImageProvider(asset, isOriginal: false))

请查看示例以了解它如何进行展示。

注册资源变化回调

AssetPicker.registerObserve(); // 注册回调
AssetPicker.unregisterObserve(); // 取消注册回调

类介绍 💭

AssetEntity

/// Android: Database _id column
/// iOS    : `PhotoKit > PHObject > localIdentifier`
String id;

/// Android: `MediaStore.MediaColumns.DISPLAY_NAME`
/// iOS    : `PHAssetResource.filename`. Nullable
/// If you must need it, See [FilterOption.needTitle] or use [titleAsync].
String title;

/// Android: title
/// iOS    : [PHAsset valueForKey:@"filename"]
Future<String> get titleAsync;

/// * 1: [AssetType.image]
/// * 2: [AssetType.video]
/// * 3: [AssetType.audio]
/// * default: [AssetType.other]
AssetType get type;

/// Asset type int value.
int typeInt;

/// Duration of video, the unit is second.
/// If [type] is [AssetType.image], then it's value is 0.
/// See also: [videoDuration].
int duration;

/// Width of the asset.
int width;

/// Height of the asset.
int height;

/// Location information when shooting. Nullable.
/// When the device is Android 10 or above, it's ALWAYS null.
/// See also: [longitude].
double get latitude => _latitude ?? 0;
/// Also with a setter.

/// Get lat/lng from `MediaStore`(Android) / `Photos`(iOS).
/// In Android Q, this comes from EXIF.
Future<LatLng> latlngAsync();

/// Get [File] object.
/// Notice that this is not the origin file, so when it comes to some
/// scene like reading a GIF's file, please use `originFile`, or you'll
/// get a JPG.
Future<File> get file async;

/// Get the original [File] object.
Future<File> get originFile async;

/// The raw data for the entity, it may be large.
/// This property is NOT RECOMMENDED for video assets.
Future<Uint8List> get originBytes;

/// The thumbnail data for the entity. Usually use for displaying a thumbnail image widget.
Future<Uint8List> get thumbData;

/// Get thumbnail data with specific size.
Future<Uint8List> thumbDataWithSize(
  int width,
  int height, {
  ThumbFormat format = ThumbFormat.jpeg,
  int quality = 100,
});

/// Get the asset's size. Nullable if the manager is null,
Size get size;

/// If the asset is deleted, return false.
Future<bool> get exists => PhotoManager._assetExistsWithId(id);

/// The url is provided to some video player. Such as [flutter_ijkplayer](https://pub.dev/packages/flutter_ijkplayer)
///
/// Android: `content://media/external/video/media/894857`
/// iOS    : `file:///var/mobile/Media/DCIM/118APPLE/IMG_8371.MOV` in iOS.
Future<String> getMediaUrl();

/// Refresh the properties for the entity.
Future<AssetEntity> refreshProperties() async;

常见问题 ❔

xxx 版本获取冲突 (例如 dartx)

dartx 或其他依赖可能因为某些原因使用了与你的项目不同的版本。如果你遇到了与下面内容类似的错误::

Because dartx >=0.2.0 <0.5.0 depends on collection >=1.14.11 <1.15.0 and every version of flutter from sdk depends on collection 1.15.0-nullsafety, dartx >=0.2.0 <0.5.0 is incompatible with flutter from sdk.
So, because wechat_assets_picker_demo depends on both flutter any from sdk and dartx ^0.4.2, version solving failed.

将以下代码添加至你的 pubspec.yaml

dependency_overrides:
  dartx: ^0.4.2

如何获取资源的路径以进行上传或编辑等操作的整合?

你不需要获得路径(也许)。

File 对象可以通过 entity.originFile 获得,如果需要 Uint8List 则使用 entity.originBytes

如果再此之后你仍然需要路径,那么可以通过已获得的 File 对象获取: file.absolutePath

如何更改“Recent”或其他路径的名称或属性?

photo_manager 传递的 “Recent” 路径,包含了您设备上的所有的 AssetEntity。大部分的平台都会将这个路径命名为 “Recent”。尽管我们提供了自定义文字构建的能力,但是 AssetPathEntity 的名字或属性只能通过 SortPathDelegate 进行更改。这是你能访问到所有 AssetPathEntity 的唯一方法,或者说,是现阶段我们暴露出来的唯一方法。

若需要更改某一个路径的名字,继承 SortPathDelegate 并实现你自己的构建,接着像如下代码一样进行编写:

/// 构建你自己的排序
class CustomSortPathDelegate extends SortPathDelegate {
  const CustomSortPathDelegate();

  @override
  void sort(List<AssetPathEntity> list) {
    ///...///

    // 在这里你可以对每个你认为需要的路径进行判断。
    // 我们唯一推荐更改的属性是 [name],
    // 并且我们不对更改其他属性造成的问题负责。
    for (final AssetPathEntity entity in list) {
      // 如果这个路径的 `isAll` 为真,则该路径就是你需要的。
      if (entity.isAll) {
        entity.name = '最近';
      }
    }

    ///...///
  }
}

将你的构建传递至静态调用方法里,而后你就会看到你自定义了名称的路径。

FileUint8List创建AssetEntity的方法

如果需要使用此库结合一些拍照需求,可通过以下方法将FileUint8List转为AssetEntity

final File file = your_file; // 你的File对象
final Uint8List byteData = await file.readAsBytes(); // 转为Uint8List
final AssetEntity imageEntity = await PhotoManager.editor.saveImage(byteData); // 存入手机并生成AssetEntity

如果不想保留文件,可以在操作完成(上传完或业务处理完)后进行删除:

final List<String> result = await PhotoManager.editor.deleteWithIds([entity.id]);

参考文档: flutter_photo_manager#insert-new-item

控制台提示 'Failed to find GeneratedAppGlideModule'

W/Glide   (21133): Failed to find GeneratedAppGlideModule. You should include an annotationProcessor complie dependency on com.github.bumptech.glide:compiler in you application ana a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored.

Glide 通过注解来保证单例,防止单例或版本之间的冲突,而因为photo_manager使用了Glide提供部分图片功能,所以使用它的项目必须实现自己的AppGlideModule。 请移步Android部分了解如何实现。

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [2020] [AlexV525] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

天马工厂组件库,公司在融媒体发布端系统软件研发与整体解决方案 展开 收起
README
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/tmgc/flutter_wechat_assets_picker.git
git@gitee.com:tmgc/flutter_wechat_assets_picker.git
tmgc
flutter_wechat_assets_picker
flutter_wechat_assets_picker
master

搜索帮助