本文介绍了如何在Flutter中将gridView项居中放置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个4 * 4的网格视图,但是有时不是16个项目,而是可能只有15个项目,到最后一行看起来不太好...

I have a 4*4 grid view, but sometimes instead of 16 items there might only be 15 items, to the last row looks not so nice...

我想知道有什么方法可以使gridView行中的项居中吗?还是可能有其他解决方案可以解决我的任务?

I am wondered is there any way to center items in gridView row?Or there might be some other solution which can solve my task?

推荐答案

作为选项,您可以使用Wrap小部件代替Grid这是一个例子

as an option you can use Wrap widget instead of Gridhere is an example

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Title')),
        body: AlignedGrid(),
      ),
    );
  }
}

class AlignedGrid extends StatelessWidget {
  final double runSpacing = 4;
  final double spacing = 4;
  final int listSize = 15;
  final columns = 4;

  @override
  Widget build(BuildContext context) {
    final w = (MediaQuery.of(context).size.width - runSpacing * (columns - 1)) / columns;
    return SingleChildScrollView(
      child: Wrap(
        runSpacing: runSpacing,
        spacing: spacing,
        alignment: WrapAlignment.center,
        children: List.generate(listSize, (index) {
          return Container(
            width: w,
            height: w,
            color: Colors.green[200],
          );
        }),
      ),
    );
  }
}

根据需要更改alignment属性例如WrapAlignment.spaceEvenly

change alignment property as you wishe.g. WrapAlignment.spaceEvenly

这篇关于如何在Flutter中将gridView项居中放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:06