'GridView does not cover background if totalWidth is not dividable by crossAxisCount
I created a GridView with crossAxisCount: 3. The problem is that if the totalWidth of the GridView is not dividable by 3, the background will shine through the GridView resulting in like the background colored lines visible on the GridView. Is there a way to avoid it?
Note: Problem does not appear on mobile
Code for Reproduction:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SizedBox(
width: 301,
child: GridView.count(
crossAxisCount: 3,
children: [
for (int i = 0; i < 12; i++)
Container(
color: Colors.black,
),
],
),
),
),
);
}
}
Solution 1:[1]
This can be removed using border.
Container(
decoration: BoxDecoration(
color: Colors.black,
border: Border.all(
color: Colors.black,
),
),
),
Solution 2:[2]
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var responsive = MediaQuery.of(context).size; // add this line
return Scaffold(
body: SizedBox(
width: responsive.width, // add this line
height: responsive.height, // add this line
child: GridView.count(
crossAxisCount: 3,
children: [
for (int i = 0; i < 12; i++)
Container( // change content to view borders og grid
decoration: BoxDecoration( // add this line
border: Border.all( // add this line
color: Colors.white, // add this line
width: 1, // add this line
), // add this line
color: Colors.black, // add this line
), // add this line
),
],
),
),
);
}
}
The result will be as this:
Solution 3:[3]
or you can just put value border width = 0.0
SizedBox(
width: 301,
child: GridView.count(
crossAxisCount: 3,
children: [
for (int i = 0; i < 12; i++)
Container(
decoration: BoxDecoration(
color: Colors.black,
border: Border.all(
width: 0.0,
),
),
),
],
),
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yeasin Sheikh |
| Solution 2 | Mouaz M Shahmeh |
| Solution 3 | MohammedAli |


