Flutter图片列表展示插件image_list的使用

Flutter图片列表展示插件image_list的使用

这是用于从手机上平滑地显示图片的图片列表。

尽管目前该插件还有很多功能未包含,例如视频预览、图片裁剪等。

安装

首先,在你的pubspec.yaml文件中添加image_list作为依赖项。

此插件是为了支持我的另一个插件adv_image_picker而制作的。你可以在那里看到权限处理的相关信息。

示例

你可以在这里找到完整的示例代码:

import 'package:flutter/material.dart';
import 'package:image_list/data/media.dart';
import 'package:image_list/image_list.dart';
import 'package:image_list/plugin.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Album>? albums;
  ImageListController? controller;
  Album? currentAlbum;
  List<MediaData>? _selections;
  bool multipleMode = false;
  bool loading = true;
  List<MediaType> types = [MediaType.image, MediaType.video];

  [@override](/user/override)
  void initState() {
    super.initState();
    getAlbums();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Builder(
        builder: (BuildContext context) {
          return Scaffold(
            appBar: AppBar(
              title: const Text('Image List Example'),
            ),
            body: loading
                ? Center(child: CircularProgressIndicator())
                : albums == null
                    ? Center(child: Text('Could not load images'))
                    : Column(
                        children: [
                          Row(
                            children: [
                              Expanded(
                                child: CheckboxListTile(
                                  title: Text("获取图片"),
                                  value: types.contains(MediaType.image),
                                  onChanged: (newValue) {
                                    setState(() {
                                      loading = true;
                                      if (types.contains(MediaType.image))
                                        types.remove(MediaType.image);
                                      else
                                        types.add(MediaType.image);

                                      getAlbums();
                                    });
                                  },
                                  controlAffinity: ListTileControlAffinity.leading, //  &lt;-- leading Checkbox
                                ),
                              ),
                              Expanded(
                                child: CheckboxListTile(
                                  title: Text("获取视频"),
                                  value: types.contains(MediaType.video),
                                  onChanged: (newValue) {
                                    setState(() {
                                      loading = true;
                                      if (types.contains(MediaType.video))
                                        types.remove(MediaType.video);
                                      else
                                        types.add(MediaType.video);

                                      getAlbums();
                                    });
                                  },
                                  controlAffinity: ListTileControlAffinity.leading, //  &lt;-- leading Checkbox
                                ),
                              ),
                            ],
                          ),
                          if (currentAlbum != null)
                            DropdownButton<Album>(
                              value: currentAlbum,
                              onChanged: (Album? newAlbum) {
                                this.currentAlbum = newAlbum;
                                setState(() {
                                  if (controller != null && currentAlbum != null)
                                    this.controller!.reloadAlbum(currentAlbum!.identifier);
                                });
                              },
                              items: albums!.map<DropdownMenuItem<Album>>((Album value) {
                                return DropdownMenuItem<Album>(
                                  value: value,
                                  child: Container(
                                    width: MediaQuery.of(context).size.width - 100,
                                    child: Text("${value.name} (${value.count})", maxLines: 2),
                                  ),
                                );
                              }).toList(),
                            ),
                          TextButton(
                            child: Text(multipleMode ? "设为单选" : "设为多选"),
                            onPressed: () {
                              setState(() {
                                multipleMode = !multipleMode;
                                if (this.controller != null) this.controller!.setMaxImage(multipleMode ? null : 1);
                              });
                            },
                          ),
                          Expanded(
                            child: ImageList(
                              types: types,
                              maxImages: 1,
                              albumId: currentAlbum?.identifier ?? "",
                              onImageTapped: (count, selectedMedias) {
                                if (!multipleMode) {
                                  submit(context);
                                }
                              },
                              onListCreated: (controller) {
                                this.controller = controller;
                              },
                              selections: _selections,
                              fileNamePrefix: "AdvImageExample",
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.all(16.0),
                            child: TextButton(
                              child: Text("提交"),
                              onPressed: () => submit(context),
                            ),
                          )
                        ],
                      ),
          );
        },
      ),
    );
  }

  Future<void> submit(BuildContext context) async {
    if (this.controller != null)
      this.controller!.getSelectedMedia().then((res) {
        if (res == null) return;

        ImageListPlugin.getThumbnail(size: 100, imageUri: res.first.uri!).then((value) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (BuildContext context) {
                return Scaffold(
                  appBar: AppBar(
                    title: Text("预览"),
                  ),
                  body: Center(child: Image.memory(value)),
                );
              },
            ),
          );
        });

        // File f = File(res.first.assetId);
        // late Widget preview;
        //
        // if (res.first.type == MediaType.video) {
        //   preview = VideoPreview(videoFile: f);
        // } else {
        //   preview = ImagePreview(file: f);
        // }
        //
        // Navigator.push(
        //   context,
        //   MaterialPageRoute(
        //     builder: (BuildContext context) {
        //       return preview;
        //     },
        //   ),
        // );
      });
  }

  void getAlbums() {
    ImageListPlugin.checkPermission().then((value) {
      ImageListPlugin.getAlbums(types: types).then((albums) {
        if (this.mounted)
          setState(() {
            this.loading = false;
            this.albums = albums;
            if (this.albums != null && this.albums!.isNotEmpty) this.currentAlbum = albums!.first;
            if (controller != null && currentAlbum != null) this.controller!.reloadAlbum(currentAlbum!.identifier);
          });
      });
    });
  }
}

更多关于Flutter图片列表展示插件image_list的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter图片列表展示插件image_list的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中,展示图片列表是一个常见的需求。虽然 Flutter 本身提供了多种方式来展示图片列表,但如果你想要一个更加定制化的解决方案,可以使用第三方插件 image_list。以下是使用 image_list 插件的基本步骤和示例代码。

1. 安装 image_list 插件

首先,你需要在 pubspec.yaml 文件中添加 image_list 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  image_list: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

2. 使用 ImageList 组件

image_list 插件提供了一个 ImageList 组件,可以用于展示图片列表。你可以通过传递一个图片 URL 列表来展示图片。

以下是一个简单的示例代码:

import 'package:flutter/material.dart';
import 'package:image_list/image_list.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Image List Example'),
        ),
        body: ImageListExample(),
      ),
    );
  }
}

class ImageListExample extends StatelessWidget {
  final List<String> imageUrls = [
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/200',
    'https://via.placeholder.com/250',
    'https://via.placeholder.com/300',
    'https://via.placeholder.com/350',
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Center(
      child: ImageList(
        imageUrls: imageUrls,
        imageBuilder: (context, imageUrl) {
          return Image.network(
            imageUrl,
            fit: BoxFit.cover,
          );
        },
        itemCount: imageUrls.length,
        itemExtent: 150, // 设置每个图片的高度
        scrollDirection: Axis.horizontal, // 设置滚动方向
      ),
    );
  }
}
回到顶部