flutter实现瀑布流布局

新一
2022-07-01 / 2 评论 / 242 阅读 / 正在检测是否收录...

1、安装

  flutter_staggered_grid_view: ^0.6.1

2、引入

import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

3、效果图

l520wgi6.png
l520wpjq.png

4、完整代码


import 'dart:math';

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue, // 主题色
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('新一     瀑布流布局'),
          elevation: 0.0,
          backgroundColor: Colors.blue,
        ),
        body: MyHomePage(),
      )
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List _waterFallList = [];
  @override
  void initState() {
    super.initState();
    var randomNum = new Random();
    for(var i=0; i < 40;i++){
      _waterFallList.add(50+150*randomNum.nextDouble());
    }
    print(_waterFallList);
  }
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.all(10),
        child: MasonryGridView.count(
          // 展示几列
          crossAxisCount: 3,
          // 元素总个数
          itemCount: _waterFallList.length,
          // 单个子元素
          itemBuilder: (BuildContext context, int index) => waterCard(_waterFallList[index]),
          // 纵向元素间距
          mainAxisSpacing: 10,
          // 横向元素间距
          crossAxisSpacing: 10,
          //本身不滚动,让外面的singlescrollview来滚动
          physics:const NeverScrollableScrollPhysics(),
          shrinkWrap: true, //收缩,让元素宽度自适应
        ),
      ),
    );
  }

  Widget waterCard(double item){
    return Container(
      height: item,
      decoration: BoxDecoration(
          border:Border.all(color:Colors.lightBlue,width:2),
          borderRadius: BorderRadius.circular(10)
      ),
      child: Center(
        child: Text(item.toStringAsFixed(0)),
      ),
    );
  }
}
本文共 76 个字数,平均阅读时长 ≈ 1分钟
3

打赏

:D 获取中...

更多精彩文章,按Ctrl+D收藏本站!

评论 (2)

取消
  1. 头像
    1
    MacOS · Google Chrome
    沙发

    画图

    回复
  2. 头像
    轻羽
    Windows 10 · FireFox
    板凳

    画图

    回复