How to center gridView items in Flutter?
Asked Answered
E

1

7

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...

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?

Exequatur answered 16/9, 2019 at 10:36 Comment(1)
Can you share the screenshotGreiner
D
25

as an option you can use Wrap widget instead of Grid here 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],
          );
        }),
      ),
    );
  }
}

enter image description here

change alignment property as you wish e.g. WrapAlignment.spaceEvenly

Derwood answered 16/9, 2019 at 11:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.