Flutter自适应网格布局插件intrinsic_grid_view的使用

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

Flutter自适应网格布局插件intrinsic_grid_view的使用

intrinsic_grid_view 是一个用于Flutter的自定义GridView,它提供了具有内在宽度和高度的二维子项数组。

特性

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

GridView vs IntrinsicGridView

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

使用方法

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  intrinsic_grid_view: ^0.0.2

然后运行以下命令安装依赖:

$ flutter pub get

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),
    verticalSpace: 10,
    horizontalSpace: 10,
    children: [
        for (var scientist in scientists)
            _buildWidget(scientist),
    ]
)

IntrinsicGridView.horizontal 示例

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

组合示例

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),
                            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),
                verticalSpace: 10,
                horizontalSpace: 10,
                children: [
                    for (var scientist in scientists)
                        _buildHorizontalWidget(scientist),
                ]
            ),
        ),
    ],
)

完整示例 Demo

以下是完整的示例代码,包含 _buildWidget_buildHorizontalWidget 方法:

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

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

class MyApp extends StatelessWidget {
  @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 {
  List<ScientistModel> fetchScientists(){
    return <ScientistModel>[
      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."),
      // 其他科学家数据省略
    ];
  }

  @override
  Widget build(BuildContext context) {
    var 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),
                        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),
                  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,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
    );
  }
}

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

这个示例展示了如何使用 IntrinsicGridView 来创建自适应的网格布局,并根据不同的内容调整每个子项的大小。希望这些信息对您有所帮助!


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

1 回复

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


当然,下面是一个关于如何使用 intrinsic_grid_view 插件来实现自适应网格布局的示例代码。intrinsic_grid_view 是一个 Flutter 插件,它允许你创建响应式网格布局,能够根据不同的屏幕尺寸和方向自动调整列数。

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

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

然后,在你的 Dart 文件中,你可以使用 IntrinsicGridView 来创建一个自适应网格布局。以下是一个完整的示例:

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

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

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

class MyHomePage extends StatelessWidget {
  final List<String> items = List.generate(50, (index) => "Item ${index + 1}");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('IntrinsicGridView Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: IntrinsicGridView<String>(
          // 设置每行的最大列数,可以根据需要调整
          maxColumns: IntrinsicGridView.of(context).maxColumns,
          // 设置列间距
          crossAxisSpacing: 8.0,
          // 设置行间距
          mainAxisSpacing: 8.0,
          // 设置每个子项的大小
          itemAspectRatio: 1.0,
          // 传入数据列表
          items: items,
          // 构建每个子项的Widget
          itemBuilder: (context, index, item) {
            return Card(
              elevation: 4.0,
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(item),
              ),
            );
          },
        ),
      ),
    );
  }
}

在这个示例中:

  1. IntrinsicGridView 被用来创建一个自适应网格布局。
  2. maxColumns 属性设置为 IntrinsicGridView.of(context).maxColumns,这样可以根据当前屏幕宽度自动调整列数。
  3. crossAxisSpacingmainAxisSpacing 分别设置了列间距和行间距。
  4. itemAspectRatio 设置了每个子项的宽高比,这里设置为1.0,即宽高相等。
  5. itemBuilder 是一个回调函数,用于构建每个子项的Widget。

你可以根据实际需求调整这些参数,以实现你所需要的布局效果。

希望这个示例对你有帮助!如果你有其他问题,请随时提问。

回到顶部