Flutter九宫格图片展示插件nine_grid_view的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter九宫格图片展示插件nine_grid_view的使用

nine_grid_view 是一个用于在Flutter应用中实现类似微博动态、微信朋友圈九宫格图片展示效果的插件。它不仅支持单张大图预览,还支持群头像展示(如微信、钉钉、QQ等群组头像)。

添加依赖

首先,在你的 pubspec.yaml 文件中添加 nine_grid_view 依赖:

dependencies:
  nine_grid_view: ^2.0.0

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

示例代码

下面是一个完整的示例,展示了如何使用 NineGridViewDragSortView

主页面示例

import 'package:flutter/material.dart';
import 'package:nine_grid_view/nine_grid_view.dart';
import 'models.dart'; // 假设你有一个模型文件来处理图片数据
import 'utils.dart'; // 假设你有一个工具类来生成Widget

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _title = 'QQ Group';
  NineGridType _gridType = NineGridType.qqGp;
  List<ImageBean> imageList = [];

  @override
  void initState() {
    super.initState();
    imageList = Utils.getTestData(); // 初始化图片数据
  }

  Widget _buildItem(BuildContext context, int index) {
    int itemCount = index % 9 + 1;

    if (_gridType == NineGridType.normal ||
        _gridType == NineGridType.weiBo ||
        _gridType == NineGridType.weChat) {
      return Container(
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(width: 0.33, color: Color(0xffe5e5e5)),
          ),
        ),
        padding: EdgeInsets.all(0),
        child: NineGridView(
          margin: EdgeInsets.all(12),
          padding: EdgeInsets.all(5),
          space: 5,
          type: _gridType,
          color: Color(0XFFE5E5E5),
          itemCount: itemCount,
          itemBuilder: (BuildContext context, int index) {
            ImageBean bean = imageList[index];
            return Utils.getWidget(bean.middlePath!);
          },
        ),
      );
    }

    int total = _gridType == NineGridType.dingTalkGp ? 4 : 9;
    itemCount = index % total + 1;
    Decoration decoration = BoxDecoration(
      color: Color(0XFFE5E5E5),
      shape: BoxShape.rectangle,
      borderRadius: BorderRadius.all(Radius.circular(4)),
    );

    Widget header = NineGridView(
      width: 120,
      height: 120,
      padding: EdgeInsets.all(2),
      alignment: Alignment.center,
      space: 3,
      type: _gridType,
      decoration: _gridType == NineGridType.weChatGp ? decoration : null,
      itemCount: itemCount,
      itemBuilder: (BuildContext context, int index) {
        ImageBean bean = imageList[index];
        return Utils.getWidget(bean.middlePath!);
      },
    );

    return InkWell(
      onTap: () {},
      child: Container(
        padding: EdgeInsets.only(left: 12, top: 12, right: 12, bottom: 12),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(width: 0.33, color: Color(0xffe5e5e5)),
          ),
        ),
        child: Row(
          children: <Widget>[header],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('$_title'),
        centerTitle: true,
        actions: <Widget>[
          PopupMenuButton(
            icon: Icon(Icons.settings),
            onSelected: (value) {
              setState(() {
                _gridType = value;
                switch (value) {
                  case NineGridType.qqGp:
                    _title = 'QQ Group';
                    break;
                  case NineGridType.weChatGp:
                    _title = 'WeChat Group';
                    break;
                  case NineGridType.dingTalkGp:
                    _title = 'DingTalk Group';
                    break;
                  case NineGridType.weChat:
                    _title = 'WeChat';
                    break;
                  case NineGridType.weiBo:
                    _title = 'WeiBo Intl';
                    break;
                  case NineGridType.normal:
                    _title = 'Normal';
                    break;
                }
              });
            },
            itemBuilder: (BuildContext context) => <PopupMenuItem<NineGridType>>[
              PopupMenuItem<NineGridType>(value: NineGridType.qqGp, child: Text('QQ Group')),
              PopupMenuItem<NineGridType>(value: NineGridType.weChatGp, child: Text('WeChat Group')),
              PopupMenuItem<NineGridType>(value: NineGridType.dingTalkGp, child: Text('DingTalk Group')),
              PopupMenuItem<NineGridType>(value: NineGridType.weChat, child: Text('WeChat')),
              PopupMenuItem<NineGridType>(value: NineGridType.weiBo, child: Text('WeiBo')),
              PopupMenuItem<NineGridType>(value: NineGridType.normal, child: Text('Normal')),
            ],
          ),
        ],
      ),
      body: ListView.builder(
        physics: BouncingScrollPhysics(),
        itemCount: 9,
        padding: EdgeInsets.all(0),
        itemBuilder: (BuildContext context, int index) {
          return _buildItem(context, index);
        },
      ),
    );
  }
}

拖拽排序视图示例

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

class DragSortPage extends StatefulWidget {
  @override
  _DragSortPageState createState() => _DragSortPageState();
}

class _DragSortPageState extends State<DragSortPage> {
  List<String> imageUrls = [
    "https://example.com/image1.jpg",
    "https://example.com/image2.jpg",
    "https://example.com/image3.jpg",
    // Add more URLs as needed
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Drag Sort View")),
      body: DragSortView(
        imageUrls,
        space: 5,
        margin: EdgeInsets.all(20),
        padding: EdgeInsets.all(0),
        itemBuilder: (BuildContext context, int index) {
          return Image.network(imageUrls[index]);
        },
        initBuilder: (BuildContext context) {
          return Center(child: CircularProgressIndicator());
        },
        onDragListener: (MotionEvent event, double itemWidth) {
          if (event.globalY > 600) {
            return true; // 判断是否拖动到指定位置删除
          }
          return false;
        },
      ),
    );
  }
}

总结

通过上述示例,你可以轻松地在Flutter项目中集成九宫格图片展示功能,并根据需要进行定制化设置。nine_grid_view 插件提供了多种布局方式和丰富的配置选项,能够满足不同的业务需求。希望这个指南对你有所帮助!


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

1 回复

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


当然,以下是如何在Flutter项目中使用nine_grid_view插件来展示九宫格图片的示例代码。nine_grid_view是一个流行的Flutter插件,用于以九宫格的形式展示图片。

步骤 1: 添加依赖

首先,你需要在你的pubspec.yaml文件中添加nine_grid_view依赖。

dependencies:
  flutter:
    sdk: flutter
  nine_grid_view: ^x.y.z  # 请替换为最新版本号

运行flutter pub get来安装依赖。

步骤 2: 导入包

在你的Dart文件中导入nine_grid_view包。

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

步骤 3: 使用NineGridView

下面是一个完整的示例,展示如何使用NineGridView来展示九宫格图片。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'NineGridView Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: NineGridPage(),
    );
  }
}

class NineGridPage extends StatelessWidget {
  // 示例图片URL列表
  final List<String> imageUrls = [
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
    'https://via.placeholder.com/150',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('NineGridView Demo'),
      ),
      body: Center(
        child: NineGridView(
          imageUrls: imageUrls,
          itemCount: imageUrls.length,
          onImageClick: (index) {
            // 点击图片时的回调
            print('Image at index $index clicked');
            // 你可以在这里添加导航到详情页的代码
          },
          gap: 5.0, // 图片之间的间距
          padding: EdgeInsets.all(10.0), // 内边距
        ),
      ),
    );
  }
}

解释

  1. 依赖添加:在pubspec.yaml中添加nine_grid_view依赖。
  2. 导入包:在需要使用NineGridView的Dart文件中导入nine_grid_view包。
  3. 使用NineGridView
    • 创建一个包含图片URL的列表。
    • NineGridView中传入图片URL列表、图片数量、点击图片时的回调、图片之间的间距以及内边距。

这样,你就可以在你的Flutter应用中展示九宫格图片了。记得根据实际需要调整图片URL、间距和内边距等参数。

回到顶部