简体   繁体   English

如何在 Flutter 中将 gridView 项目居中?

[英]How to center gridView items in Flutter?

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...我有一个 4*4 的网格视图,但有时可能只有 15 个项目而不是 16 个项目,最后一行看起来不太好......

I am wondered is there any way to center items in gridView row?我想知道有没有办法将 gridView 行中的项目居中? Or there might be some other solution which can solve my task?或者可能有其他解决方案可以解决我的任务?

as an option you can use Wrap widget instead of Grid here is an example作为一个选项,您可以使用 Wrap 小部件而不是 Grid 这里是一个示例

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],
          );
        }),
      ),
    );
  }
}

在此处输入图片说明

change alignment property as you wish eg WrapAlignment.spaceEvenly根据需要更改alignment属性,例如WrapAlignment.spaceEvenly

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM