【新年快乐第二弹】在 Flutter 中使用交错网格视图创建瀑布流布局 您所在的位置:网站首页 微星主板内存xmp开一还是二 【新年快乐第二弹】在 Flutter 中使用交错网格视图创建瀑布流布局

【新年快乐第二弹】在 Flutter 中使用交错网格视图创建瀑布流布局

2022-08-31 01:21| 来源: 网络整理| 查看: 265

作者:坚果

公众号:”大前端之旅”

华为云享专家,InfoQ签约作者,阿里云专家博主,51CTO博客首席体验官,​​开源项目GVA成员之一​​,专注于大前端技术的分享,包括Flutter,小程序,安卓,VUE,JavaScript。

马上过新年了,想好如何过年了吗?,今天我带大家在瀑布流布局中写新年快乐。

在 Web 和移动开发世界中,当我们想要显示大小不相同的项目网格时,瀑布流布局很有用。一个轴使用严格的网格布局,通常是列。在另一个轴上,项目具有不同的高度,但可以灵活排列以填满可用空间。使用瀑布流布局的一个著名例子是 Pinterest。他们为他们的网站和移动应用程序实现了这种布局,以显示不同大小的图像。

本文将向您通过使用名为MasonryGridView提供一个流行的包​​fluter_staggered_grid_view​​。

应用预览

我们要构建的应用程序包含一个 3 列的瀑布流布局。每个项目都有一个随机的背景颜色和一个动态的高度。:

【新年快乐第二弹】在 Flutter 中使用交错网格视图创建瀑布流布局_前端_02

代码

通过运行安装插件:

flutter pub add flutter_staggered_grid_view

然后执行这个命令:

flutter pub get

​main.dart 中​的完整源代码及说明:

// main.dartimport 'package:flutter/material.dart';import 'dart:math';​import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';​void main() { runApp(const MyApp());}​class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);​ @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: '大前端之旅', theme: ThemeData( primarySwatch: Colors.amber, ), home: const HomePage(), ); }}​class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key);​ @override _HomePageState createState() => _HomePageState();}​class _HomePageState extends State { // Generate a list of dummy items final List _items = List.generate( 200, (index) => { "id": index, "title": " 新年快乐$index", "height": Random().nextInt(150) + 50.5 });​ @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('大前端之旅祝你新年快乐'), ), // implement the massonry layout body: MasonryGridView.count( itemCount: _items.length, padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 10), // the number of columns crossAxisCount: 3, // vertical gap between two items mainAxisSpacing: 4, // horizontal gap between two items crossAxisSpacing: 4, itemBuilder: (context, index) { // display each item with a card return Card( // Give each item a random background color color: Color.fromARGB( Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), Random().nextInt(256)), key: ValueKey(_items[index]['id']), child: SizedBox( height: _items[index]['height'], child: Center( child: Text(_items[index]['title']), ), ), ); }, )); }}​ 结论

你已经学习了如何在 Flutter 中制作瀑布流布局。在您想要构建漂亮且专业的用户界面的许多情况下,这些知识可能会有所帮助。​

大家的点赞与支持就是对我最大的鼓励。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有