Flutter响应式网格布局插件responsive_grid的使用

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

Flutter响应式网格布局插件responsive_grid的使用

responsive_grid 是一个用于Flutter的响应式网格布局插件,它可以帮助开发者在不同屏幕尺寸下实现良好的UI布局。本文将介绍如何使用该插件,并提供完整的示例代码。

安装

首先,在 pubspec.yaml 文件中添加 responsive_grid 依赖:

dependencies:
  responsive_grid: ^latest_version

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

基本用法

Responsive Grid Layout

ResponsiveGridRowResponsiveGridCol 组件提供了类似于Bootstrap的网格系统。你可以为每个列指定在不同屏幕尺寸下的宽度,总宽度默认为12。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Responsive Grid Example'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final String title;

  MyHomePage({Key? key, required this.title}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ResponsiveGridRow(
              children: [
                ResponsiveGridCol(
                  lg: 12,
                  child: Container(
                    height: 100,
                    alignment: Alignment(0, 0),
                    color: Colors.purple,
                    child: Text("lg : 12"),
                  ),
                ),
                ResponsiveGridCol(
                  xs: 6,
                  md: 3,
                  child: Container(
                    height: 100,
                    alignment: Alignment(0, 0),
                    color: Colors.green,
                    child: Text("xs : 6 \r\nmd : 3"),
                  ),
                ),
                ResponsiveGridCol(
                  xs: 6,
                  md: 3,
                  child: Container(
                    height: 100,
                    alignment: Alignment(0, 0),
                    color: Colors.orange,
                    child: Text("xs : 6 \r\nmd : 3"),
                  ),
                ),
                ResponsiveGridCol(
                  xs: 6,
                  md: 3,
                  child: Container(
                    height: 100,
                    alignment: Alignment(0, 0),
                    color: Colors.red,
                    child: Text("xs : 6 \r\nmd : 3"),
                  ),
                ),
                ResponsiveGridCol(
                  xs: 6,
                  md: 3,
                  child: Container(
                    height: 100,
                    alignment: Alignment(0, 0),
                    color: Colors.blue,
                    child: Text("xs : 6 \r\nmd : 3"),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Responsive Grid List

ResponsiveGridList 根据指定的项目宽度和间距自动调整每行项目的数量。

ResponsiveGridList(
  desiredItemWidth: 100,
  minSpacing: 10,
  children: List.generate(20, (index) => index + 1).map((i) {
    return Container(
      height: 100,
      alignment: Alignment(0, 0),
      color: Colors.cyan,
      child: Text(i.toString()),
    );
  }).toList(),
)

Responsive Staggered Grid List

ResponsiveStaggeredGridList 类似于 ResponsiveGridList,但每一项的高度可以独立设置。

ResponsiveStaggeredGridList(
  desiredItemWidth: 100,
  minSpacing: 10,
  children: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map((i) {
    return Container(
      height: ((i % 3) + 1) * 100.0,
      alignment: Alignment(0, 0),
      color: Colors.cyan,
      child: Text(i.toString()),
    );
  }).toList(),
)

Utilities

ResponsiveWidget and ResponsiveBuilder

ResponsiveWidgetResponsiveBuilder 可以根据不同的屏幕尺寸创建条件性组件。

Center(
  child: ResponsiveWidget(
    xs: Text('xs'),
    sm: Text('sm'),
    md: Text('md'),
    lg: Text('lg'),
    xl: Text('xl'),
  ),
)

ResponsiveLayoutBuilder

ResponsiveLayoutBuilder 可以为不同的屏幕尺寸创建不同的布局结构。

ResponsiveLayoutBuilder(
  xs: (BuildContext context, List<Widget> children) => Column(
    children: children,
  ),
  md: (BuildContext context, List<Widget> children) => Row(
    children: children,
  ),
  children: [...],
)

responsiveValue()

responsiveValue() 方法可以根据屏幕尺寸返回不同的值。

GridView.count(
  crossAxisCount: responsiveValue(context, xs: 2, sm: 3, md: 4, lg: 6, xl: 7),
  children: [...],
)

示例应用

以下是一个完整的示例应用,展示了如何使用 responsive_grid 插件的不同功能。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'ResponsiveGrid Examples'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              _buildTestButtonItem(context, _buildGridLayout(), "Responsive Grid Rows"),
              _buildTestButtonItem(context, _buildGridList(), "Responsive Grid List"),
              _buildTestButtonItem(context, _resposiveWidgetTest(), "ResponsiveWidget"),
              _buildTestButtonItem(context, _resposiveValueTest(), "responsiveValue method"),
              _buildTestButtonItem(context, _resposiveBuilderTest(), "ResponsiveBuilder"),
              _buildTestButtonItem(context, _buildStaggeredGridList(), "StaggeredGridList"),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTestButtonItem(BuildContext context, Widget widget, String name) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: ElevatedButton(
        onPressed: () => Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ExamplePage(title: name, child: widget)),
        ),
        child: Text(name),
      ),
    );
  }

  Widget _buildGridList() {
    return ResponsiveGridList(
      desiredItemWidth: 100,
      minSpacing: 10,
      children: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map((i) {
        return Container(
          height: 100.0,
          alignment: Alignment(0, 0),
          color: Colors.cyan,
          child: Text(i.toString()),
        );
      }).toList(),
    );
  }

  Widget _buildGridLayout() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        ResponsiveGridRow(
          children: [
            ResponsiveGridCol(
              lg: 12,
              child: Container(
                height: 100,
                alignment: Alignment(0, 0),
                color: Colors.purple,
                child: Text("lg : 12"),
              ),
            ),
            ResponsiveGridCol(
              xs: 6,
              md: 3,
              child: Container(
                height: 100,
                alignment: Alignment(0, 0),
                color: Colors.green,
                child: Text("xs : 6 \r\nmd : 3"),
              ),
            ),
            // 其他列...
          ],
        ),
      ],
    );
  }

  Widget _resposiveWidgetTest() {
    return Center(
      child: ResponsiveWidget(
        xs: Text('xs'),
        sm: Text('sm'),
        md: Text('md'),
        lg: Text('lg'),
        xl: Text('xl'),
      ),
    );
  }

  Widget _resposiveValueTest() {
    return Center(
      child: Text(responsiveValue(context, xs: 'xs', lg: 'lg', md: 'md', sm: 'sm', xl: 'xl')),
    );
  }

  Widget _resposiveBuilderTest() {
    return Center(
      child: ResponsiveBuilder(
        child: Text(
          'child',
          style: TextStyle(fontSize: 30),
        ),
        xs: (_, child) => Container(alignment: Alignment.topRight, child: child),
        sm: (_, child) => Container(alignment: Alignment.topLeft, child: child),
        md: (_, child) => Container(alignment: Alignment.center, child: child),
        lg: (_, child) => Container(alignment: Alignment.bottomRight, child: child),
        xl: (_, child) => Container(alignment: Alignment.bottomLeft, child: child),
      ),
    );
  }

  Widget _buildStaggeredGridList() {
    return ResponsiveStaggeredGridList(
      desiredItemWidth: 100,
      minSpacing: 10,
      children: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map((i) {
        return Container(
          height: ((i % 3) + 1) * 100.0,
          alignment: Alignment(0, 0),
          color: Colors.cyan,
          child: Text(i.toString()),
        );
      }).toList(),
    );
  }
}

class ExamplePage extends StatelessWidget {
  final String title;
  final Widget child;

  ExamplePage({required this.title, required this.child});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: child,
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用responsive_grid插件来实现响应式网格布局的示例代码。

首先,确保你已经在pubspec.yaml文件中添加了responsive_grid依赖:

dependencies:
  flutter:
    sdk: flutter
  responsive_grid: ^x.y.z  # 请将x.y.z替换为当前最新版本号

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

以下是一个简单的示例,展示了如何使用responsive_grid来创建一个响应式网格布局:

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

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

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

class ResponsiveGridDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Responsive Grid Demo'),
      ),
      body: GridView.builder(
        gridDelegate: ResponsiveGridDelegate(
          crossAxisCount: [
            ResponsiveCrossAxisCount(min: 1, max: 1, span: 1, on: ScreenSize.small),
            ResponsiveCrossAxisCount(min: 2, max: 2, span: 1, on: ScreenSize.medium),
            ResponsiveCrossAxisCount(min: 3, max: 4, span: 1, on: ScreenSize.large),
          ],
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        itemCount: 20,
        itemBuilder: (context, index) {
          return Card(
            color: Colors.primary.withOpacity(0.7),
            child: Center(
              child: Text(
                'Item $index',
                style: TextStyle(color: Colors.white),
              ),
            ),
          );
        },
      ),
    );
  }
}

代码说明:

  1. 依赖导入:导入flutter/material.dartresponsive_grid/responsive_grid.dart
  2. MaterialApp:创建一个基本的Flutter应用。
  3. ResponsiveGridDemo:这是我们的主页面,包含一个ScaffoldAppBar
  4. GridView.builder:使用GridView.builder来创建网格视图。
  5. ResponsiveGridDelegate:定义网格的布局。我们为不同的屏幕尺寸(小、中、大)设置了不同的列数。ResponsiveCrossAxisCount类允许我们定义在不同屏幕尺寸下网格的最小、最大列数以及每列的跨度。
  6. crossAxisSpacingmainAxisSpacing:设置网格项之间的水平和垂直间距。
  7. itemBuilder:定义了每个网格项的内容,这里我们简单地使用了一个带有文本的Card

注意事项:

  • 确保responsive_grid插件的版本是最新的,以避免兼容性问题。
  • 根据你的需求调整ResponsiveCrossAxisCount中的参数,以实现不同的响应式布局。

这个示例展示了如何使用responsive_grid插件来创建一个基本的响应式网格布局。你可以根据需要进一步自定义和扩展这个布局。

回到顶部