Flutter自定义网格布局插件custom_intrinsic_grid_view的使用

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

Flutter 自定义网格布局插件 custom_intrinsic_grid_view 的使用

IntrinsicGridView

IntrinsicGridView 提供了一个具有固定宽度和高度的二维数组子组件。

它有两个命名构造函数:

  • IntrinsicGridView.vertical:垂直滚动。
  • IntrinsicGridView.horizontal:水平滚动。

GridView vs IntrinsicGridView

属性 GridView IntrinsicGridView
内容溢出
子组件宽度随项目宽度变化
子组件高度随项目高度变化
如果任何子组件的高度不同,则相邻的子组件会设置新的高度

使用

1. 添加依赖

在命令行中运行以下命令:

$ flutter pub add intrinsic_grid_view

或者在 pubspec.yaml 文件的 dependencies: 部分添加以下包:

dependencies:
  intrinsic_grid_view: ^0.0.2

2. 导入库

在你的 Dart 文件中导入库:

import 'package:intrinsic_grid_view/intrinsic_grid_view.dart';

3. 示例

IntrinsicGridView.vertical 示例

代码:

IntrinsicGridView.vertical(
  padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
  // columnCount: 3,
  verticalSpace: 10,
  horizontalSpace: 10,
  children: [
    for (var scientist in scientists)
      _buildWidget(scientist),
  ]
), // IntrinsicGridView.vertical

IntrinsicGridView.horizontal 示例

代码:

IntrinsicGridView.horizontal(
  padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
  // rowCount: 1,
  verticalSpace: 10,
  horizontalSpace: 10,
  children: [
    for (var scientist in scientists)
      _buildHorizontalWidget(scientist),
  ]
), // IntrinsicGridView.horizontal

IntrinsicGridView.vertical + IntrinsicGridView.horizontal 示例

代码:

Column(
  children: [
    Expanded(
      flex: 3,
      child: Row(
        children: [
          Expanded(
            child: IntrinsicGridView.vertical(
              padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
              columnCount: 1,
              verticalSpace: 10,
              horizontalSpace: 10,
              children: [
                for (var scientist in scientists)
                  _buildWidget(scientist),
              ]
            ), // IntrinsicGridView.vertical
          ),

          Expanded(
            child: IntrinsicGridView.vertical(
              padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
              // columnCount: 3,
              verticalSpace: 10,
              horizontalSpace: 10,
              children: [
                for (var scientist in scientists)
                  _buildWidget(scientist),
              ]
            ), // IntrinsicGridView.vertical
          ),
        ],
      ),
    ),

    Expanded(
      child: IntrinsicGridView.horizontal(
        padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
        // rowCount: 1,
        verticalSpace: 10,
        horizontalSpace: 10,
        children: [
          for (var scientist in scientists)
            _buildHorizontalWidget(scientist),
        ]
      ), // IntrinsicGridView.horizontal
    ),
  ],
),

贡献

建议和拉取请求都欢迎。对于重大更改,请先打开一个议题讨论你想要进行的更改。

开发团队

许可证

Apache 2.0


完整示例 Demo

main.dart

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Example IntrinsicGirdView',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      debugShowCheckedModeBanner: false,
      home: ExampleScreen(),
    );
  }
}

class ExampleScreen extends StatelessWidget {
  var size;

  [@override](/user/override)
  Widget build(BuildContext context) {
    size = MediaQuery.of(context).size;

    List<ScientistModel> scientists = fetchScientists();

    return Scaffold(
      appBar: AppBar(
        foregroundColor: Colors.white,
        backgroundColor: Colors.blueGrey.shade700,
        title: Text('IntrinsicGridView Example'),
      ),
      body: Container(
        color: Colors.blueGrey.shade900,
        child: Column(
          children: [
            Expanded(
              flex: 3,
              child: Row(
                children: [
                  Expanded(
                    child: IntrinsicGridView.vertical(
                      padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
                      columnCount: 1,
                      verticalSpace: 10,
                      horizontalSpace: 10,
                      children: [
                        for (var scientist in scientists)
                          _buildWidget(scientist),
                      ]
                    ),
                  ),
                  Expanded(
                    child: IntrinsicGridView.vertical(
                      padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
                      // columnCount: 3,
                      verticalSpace: 10,
                      horizontalSpace: 10,
                      children: [
                        for (var scientist in scientists)
                          _buildWidget(scientist),
                      ]
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: IntrinsicGridView.horizontal(
                padding: EdgeInsets.only(top: 16, bottom: 12, left: 12, right: 12),
                // rowCount: 1,
                verticalSpace: 10,
                horizontalSpace: 10,
                children: [
                  for (var scientist in scientists)
                    _buildHorizontalWidget(scientist),
                ]
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildWidget(ScientistModel scientist) {
    double radius = 5.0;

    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(radius))
      ),
      elevation: 30,
      shadowColor: Colors.lightBlueAccent,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(radius),
              topRight: Radius.circular(radius),
            ),
            child: Image.network(
              "${scientist.image}",
              fit: BoxFit.cover,
              width: double.infinity,
              height: 120,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(right: 4, left: 8, bottom: 8, top: 8),
            child: Text(
              scientist.name,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(right: 4, left: 8, bottom: 8),
            child: Text(
              scientist.desc,
              style: TextStyle(
                fontSize: 12,
              ),
            ),
          ),
        ],
      )
    );
  }

  Widget _buildHorizontalWidget(ScientistModel scientist) {
    double radius = 5.0;

    return Card(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(radius))
      ),
      elevation: 30,
      shadowColor: Colors.lightBlueAccent,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(radius),
              bottomLeft: Radius.circular(radius),
            ),
            child: Image.network(
              "${scientist.image}",
              fit: BoxFit.cover,
              width: 120,
              height: double.infinity,
            ),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(right: 4, left: 8, bottom: 4, top: 4),
                  child: Text(
                    scientist.name,
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 4, left: 8, bottom: 8),
                  child: Text(
                    scientist.desc,
                    style: TextStyle(
                      fontSize: 12,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      )
    );
  }

  List<ScientistModel> fetchScientists() {
    return [
      ScientistModel('Alain Aspect', 'https://res.cloudinary.com/highereducation/image/upload/w_120,h_160,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/alain-aspect.jpg', "Alain Aspect holds the Augustin Fresnel Chair at the Institut d'Optique."),
      ScientistModel('David Baltimore', 'https://res.cloudinary.com/highereducation/image/upload/w_125,h_175,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/david-baltimore.jpg', "David Baltimore is currently Professor of Biology at the California Institute of Technology."),
      ScientistModel('John Tyler Bonner', 'https://res.cloudinary.com/highereducation/image/upload/w_120,h_137,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/john-tyler-bonner.jpg', "John Tyler Bonner is one of the world's leading biologists, primarily known for his work in the use of cellular slime molds to understand evolution."),
      ScientistModel('Dennis Bray', 'https://res.cloudinary.com/highereducation/image/upload/w_130,h_170,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/dennis-bray.jpg', "Dennis Bray is a professor emeritus in the Department of Physiology, Development, and Neuroscience at the University of Cambridge."),
      ScientistModel('Sydney Brenner', 'https://res.cloudinary.com/highereducation/image/upload/w_130,h_170,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/sydney-brenner.jpg', "Sydney Brenner is a biologist and the winner of the 2002 Nobel Prize in Physiology or Medicine,"),
      ScientistModel('Pierre Chambon', 'https://res.cloudinary.com/highereducation/image/upload/w_160,h_160,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/pierre-chambon.jpg', "Pierre Chambon is professor at the University of Strasbourg's Institute for Advanced Study."),
      ScientistModel('Simon Conway Morris', 'https://res.cloudinary.com/highereducation/image/upload/w_130,h_170,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/simon-conway-morris.jpg', "Simon Conway Morris is Chair of Evolutionary Palaeobiology in the Earth Sciences Department at Cambridge University."),
      ScientistModel('Mildred S. Dresselhaus', 'https://res.cloudinary.com/highereducation/image/upload/w_160,h_160,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/mildred-dresselhouse.jpg', "Mildred S. Dresselhaus is a professor of physics and electrical engineering"),
      ScientistModel('Allen J. Bard', 'https://res.cloudinary.com/highereducation/image/upload/w_160,h_165,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/allan-j-bard.jpg', 'Allen J. Bard is a professor at the University of Texas, where he also serves as director of the Center for Electrochemistry and holds the Norman Hackerman-Welch Regents Chair. He received his Ph.D. from Harvard University in 1958.'),
      ScientistModel('Timothy Berners-Lee', 'https://res.cloudinary.com/highereducation/image/upload/w_130,h_175,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/timothy-berners-lee.jpg', 'Timothy Berners-Lee is a computer scientist, best known as the inventor of the World Wide Web. He was honored as the "Inventor of the World Wide Web" during the 2012 Summer Olympics opening ceremony.'),
      ScientistModel('Gerald M. Edelman', 'https://res.cloudinary.com/highereducation/image/upload/w_160,h_145,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/gerald-m-edelman1.jpg', "Gerald M. Edelman is a biologist, immunologist, and neuroscientist."),
      ScientistModel('Ronald M. Evans', 'https://res.cloudinary.com/highereducation/image/upload/w_130,h_180,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/ronald-m-evans.jpg', "Ronald M. Evans is the March of Dimes Chair in Molecular and Developmental Biology at the Salk Institute for Biological Studies in San Diego."),
      ScientistModel('Jane Goodall', 'https://res.cloudinary.com/highereducation/image/upload/w_130,h_170,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/jane-goodall.jpg', "Jane Goodall is a primatologist, ethologist, and anthropologist."),
      ScientistModel('Leroy Hood', 'https://res.cloudinary.com/highereducation/image/upload/w_140,h_160,c_fill,f_auto,fl_lossy,q_auto/v1/TheBestSchools.org/leroy-hood.jpg', "Leroy Hood is co-founder and President of the Institute for Systems Biology.")
    ];
  }
}

class ScientistModel {
  String name;
  String image;
  String desc;
  ScientistModel(this.name, this.image, this.desc);
}

更多关于Flutter自定义网格布局插件custom_intrinsic_grid_view的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义网格布局插件custom_intrinsic_grid_view的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用custom_intrinsic_grid_view插件来创建自定义网格布局的一个代码示例。custom_intrinsic_grid_view是一个强大的插件,允许你根据子项的内容动态调整网格布局。

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

dependencies:
  flutter:
    sdk: flutter
  custom_intrinsic_grid_view: ^最新版本号  # 请替换为实际最新版本号

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

接下来,在你的Flutter应用中,你可以使用CustomIntrinsicGridView来创建一个自定义网格布局。以下是一个完整的示例代码:

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

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

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Intrinsic Grid View Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: CustomIntrinsicGridView(
          // 设置网格的主轴方向
          scrollDirection: Axis.horizontal,
          // 设置网格交叉轴的方向
          crossAxisDirection: CrossAxisDirection.down,
          // 设置网格交叉轴的对齐方式
          crossAxisAlignment: CrossAxisAlignment.start,
          // 设置网格的主轴间距
          mainAxisSpacing: 8.0,
          // 设置网格的交叉轴间距
          crossAxisSpacing: 8.0,
          // 子项的大小计算方式
          gridDelegate: SliverIntrinsicGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,  // 交叉轴方向的子项数量
            crossAxisSpacing: 8.0,
            mainAxisSpacing: 8.0,
          ),
          // 子项列表
          children: List.generate(20, (index) {
            return Card(
              color: Colors.primary.shade300,
              child: Center(
                child: Text(
                  'Item $index',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            );
          }),
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们创建了一个MaterialApp并设置了主题。
  2. MyHomePage中,我们使用Scaffold来构建页面结构,其中包含一个AppBar和一个Padding包裹的CustomIntrinsicGridView
  3. CustomIntrinsicGridViewgridDelegate使用了SliverIntrinsicGridDelegateWithFixedCrossAxisCount,它允许我们固定交叉轴方向上的子项数量,并设置主轴和交叉轴的间距。
  4. children属性包含了一个生成的列表,其中每个列表项都是一个Card,显示不同的文本内容。

这个示例展示了如何使用custom_intrinsic_grid_view插件来创建一个动态调整的子项网格布局。你可以根据需要调整gridDelegate的属性以及子项的内容来实现不同的布局效果。

回到顶部