Flutter响应式布局插件flutter_responsive_flex_grid的使用

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

Flutter响应式布局插件flutter_responsive_flex_grid的使用

Flutter Responsive Flex Grid

build

这是一个用于创建类似于Bootstrap响应式网格设计的Flutter包。

  • 可以添加带有权重宽度的网格项
  • 可以为不同的设备(xs: 超小屏幕,sm: 小屏幕,md: 中等屏幕,lg: 大屏幕,xl: 超大屏幕,xxl: 超超大屏幕)设置权重宽度
  • 可以在网格项之间添加间距

示例动画 iOS 示例 Android 示例

安装

将此包作为库使用。

添加依赖

运行以下命令:

flutter pub add flutter_responsive_flex_grid

这将在你的pubspec.yaml文件中添加如下行(并隐式运行dart pub get):

dependencies:
  flutter_responsive_flex_grid: ^0.0.1

或者,你可以通过编辑器支持的flutter pub get来完成。请参阅您的编辑器文档以了解更多信息。

导入

现在可以在Dart代码中使用以下导入语句:

import 'package:flutter_responsive_flex_grid/flutter_responsive_flex_grid.dart';

使用

使用ResponsiveGrid小部件创建响应式网格,并附加ResponsiveGridItem作为子项。

ResponsiveGrid(
    gridSpacing: 8, // 网格项之间的间距
    children: [
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.red), // 创建一个红色容器
        xs: 50, // 在超小屏幕上占50%的宽度
        sm: 60, // 在小屏幕上占60%的宽度
        md: 70, // 在中等屏幕上占70%的宽度
        lg: 80, // 在大屏幕上占80%的宽度
        xl: 90, // 在超大屏幕上占90%的宽度
        xxl: 100, // 在超超大屏幕上占100%的宽度
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.green), // 创建一个绿色容器
        xs: 50,
        sm: 60,
        md: 70,
        lg: 80,
        xl: 90,
        xxl: 100,
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.blue), // 创建一个蓝色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.grey), // 创建一个灰色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.black), // 创建一个黑色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.red), // 创建一个红色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.green), // 创建一个绿色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.blue), // 创建一个蓝色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.grey), // 创建一个灰色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.black), // 创建一个黑色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.yellowAccent), // 创建一个黄色容器
      ),
      ResponsiveGridItem(
        child: _buildColorContainer(Colors.tealAccent), // 创建一个青色容器
      ),
    ]
)

其中_buildColorContainer函数定义如下:

Widget _buildColorContainer(Color color) {
  return Container(
    color: color,
    height: 100,
    width: double.infinity,
    child: Center(child: Text(color.toString())),
  );
}

示例代码

以下是完整的示例代码,展示了如何在实际项目中使用flutter_responsive_flex_grid

import 'package:flutter/material.dart';
import 'package:flutter_responsive_flex_grid/flutter_responsive_flex_grid.dart';
import 'package:responsive_flex_grid/model/planets.dart';
import 'package:responsive_flex_grid/widgets/banner.dart';
import 'package:responsive_flex_grid/widgets/contact_us.dart';
import 'package:responsive_flex_grid/widgets/footer.dart';
import 'package:responsive_flex_grid/widgets/planet_cards.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(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  late List<ResponsiveGridItem> list;
  late List<Planets> _planetList;

  [@override](/user/override)
  void initState() {
    _planetList = [
      Planets(
          name: 'Mercury',
          description: 'Mercury - the smallest planet in our solar system and closest to the Sun - is only slightly larger than Earth’s Moon. Mercury is the fastest planet, zipping around the Sun every 88 Earth days.',
          earthDays: '88 Earth Days',
          url: 'assets/images/mercury.jpeg'),
      Planets(
          name: 'Venus',
          description: 'Venus spins slowly in the opposite direction from most planets. A thick atmosphere traps heat in a runaway greenhouse effect, making it the hottest planet in our solar system.',
          earthDays: '225 Earth Days',
          url: 'assets/images/venus.jpeg'),
      Planets(
          name: 'Earth',
          description: 'Earth - our home planet - is the only place we know of so far that’s inhabited by living things. It’s also the only planet in our solar system with liquid water on the surface.',
          earthDays: '365.25 Days',
          url: 'assets/images/earth.jpeg'),
      Planets(
          name: 'Mars',
          description: 'Mars is a dusty, cold, desert world with a very thin atmosphere. There is strong evidence Mars was - billions of years ago - wetter and warmer, with a thicker atmosphere.',
          earthDays: '1.88 Earth Years',
          url: 'assets/images/mars.jpeg'),
      Planets(
          name: 'Jupiter',
          description: 'Jupiter is more than twice as massive than the other planets of our solar system combined. The giant planet’s Great Red spot is a centuries-old storm bigger than Earth.',
          earthDays: '11.86 Earth Years',
          url: 'assets/images/jupiter.jpeg'),
      Planets(
          name: 'Saturn',
          description: 'Adorned with a dazzling, complex system of icy rings, Saturn is unique in our solar system. The other giant planets have rings, but none are as spectacular as Saturn’s.',
          earthDays: '29.45 Earth Years',
          url: 'assets/images/saturn.jpeg'),
      Planets(
          name: 'Uranus',
          description: 'Uranus - seventh planet from the Sun - rotates at a nearly 90-degree angle from the plane of its orbit. This unique tilt makes Uranus appear to spin on its side.',
          earthDays: '84 Earth Years',
          url: 'assets/images/uranus.jpeg'),
      Planets(
          name: 'Neptune',
          description: 'Neptune - the eighth and most distant major planet orbiting our Sun - is dark, cold and whipped by supersonic winds. It was the first planet located through mathematical calculations, rather than by telescope.',
          earthDays: '164.82 Earth Years',
          url: 'assets/images/neptune.jpeg')
    ];
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF8F8F8),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              PlanetBanner(),
              SizedBox(height: 56),
              Container(
                margin: EdgeInsets.only(left: 16, right: 16),
                child: Text('Planets in Our Solar System',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.headline4?.copyWith(
                        fontSize: 36,
                        fontWeight: FontWeight.w600,
                        color: Colors.black)),
              ),
              SizedBox(height: 16),
              Container(
                width: 600,
                margin: EdgeInsets.only(left: 16, right: 16),
                alignment: Alignment.center,
                child: Text(
                  'An overview of the history, mythology and current scientific knowledge of the planets, moons and other objects in our solar system.',
                  style: TextStyle(
                    fontSize: 16,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
              SizedBox(height: 32),
              ResponsiveGrid(gridSpacing: 32, children: [
                ..._planetList
                    .map((item) => ResponsiveGridItem(
                        xs: 100 / 1,
                        sm: 100 / 2,
                        md: 100 / 3,
                        lg: 100 / 4,
                        xl: 100 / 5,
                        xxl: 100 / 6,
                        child: PlanetCard(obj: item)))
                    .toList()
              ]),
              ContactUs(),
              Footer(),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,下面是一个关于如何使用 flutter_responsive_flex_grid 插件来实现响应式布局的示例代码。flutter_responsive_flex_grid 是一个 Flutter 插件,它允许开发者以简单的方式创建响应式网格布局。

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

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

然后,运行 flutter pub get 来获取依赖。

接下来是一个简单的示例代码,展示如何使用 flutter_responsive_flex_grid 来创建一个响应式网格布局:

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

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

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Responsive Flex Grid Demo'),
      ),
      body: Center(
        child: ResponsiveFlexGrid(
          rows: 2,
          cols: [
            FlexibleColumn(
              flex: 2,
              children: [
                ItemWidget(title: 'Item 1', color: Colors.red),
                ItemWidget(title: 'Item 2', color: Colors.green),
              ],
            ),
            FlexibleColumn(
              flex: 1,
              children: [
                ItemWidget(title: 'Item 3', color: Colors.blue),
              ],
            ),
          ],
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          responsiveConfigs: [
            ResponsiveConfig(
              breakpoint: 800,
              cols: [
                FlexibleColumn(
                  flex: 1,
                  children: [
                    ItemWidget(title: 'Item 1', color: Colors.red),
                  ],
                ),
                FlexibleColumn(
                  flex: 1,
                  children: [
                    ItemWidget(title: 'Item 2', color: Colors.green),
                  ],
                ),
                FlexibleColumn(
                  flex: 1,
                  children: [
                    ItemWidget(title: 'Item 3', color: Colors.blue),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class ItemWidget extends StatelessWidget {
  final String title;
  final Color color;

  const ItemWidget({Key? key, required this.title, required this.color}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      margin: EdgeInsets.all(10),
      padding: EdgeInsets.all(20),
      child: Center(
        child: Text(title, style: TextStyle(color: Colors.white, fontSize: 20)),
      ),
    );
  }
}

在这个示例中:

  1. 我们定义了一个 ResponsiveFlexGrid,它有两个行 (rows: 2) 和两个列 (cols),其中第一列 (flex: 2) 占据的空间是第二列 (flex: 1) 的两倍。
  2. 每个列包含了一些 ItemWidget,这些 ItemWidget 只是简单的容器,带有不同的颜色和标题。
  3. 我们还定义了一个响应式配置 (responsiveConfigs),当屏幕宽度小于 800 时,布局会重新排列为三列,每列占据相同的空间 (flex: 1)。

这个示例展示了如何使用 flutter_responsive_flex_grid 来创建简单的响应式布局,并且可以根据不同的屏幕尺寸进行适配。你可以根据需要进一步调整和扩展这个示例。

回到顶部