Reputation: 470
I want to make the individual columns of my GridView clickable. I don't quite understand how I could do this with GestureDetector/InkWell. I don't understand how to access a whole column of a grid.
How can I do this (if this is even possible using GridView)? If it's not possible, what's the best way I could do this?
GridView.count(
crossAxisCount: 10,
children: List.generate(
50,
(_) {
return Container(
color: mainColor,
child: Container(
decoration: BoxDecoration(
color: Colors.white60,
shape: BoxShape.circle,
),
),
);
},
),
)
Upvotes: 3
Views: 3704
Reputation: 7889
By using InkWell
as a child and a little bit of math:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final appTitle = 'Column selecion demonstration';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: appTitle,
home: MyHomePage(title: appTitle),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int selectedIndex = -1;
int columnsCount = 10 ;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: GridView.count(
crossAxisCount: columnsCount,
children: List.generate(
50, ( index ) {
return InkWell(
onTap: (){
setState(() {
if(selectedIndex != index){
selectedIndex = index ;
}else{
selectedIndex = -1 ;
}
});
},
child: Container(
color: (selectedIndex % columnsCount == index % columnsCount) && selectedIndex != -1 ? Colors.blue : Colors.yellow,
child: Container(
decoration: BoxDecoration(
color: Colors.white60,
shape: BoxShape.circle,
),
),
),
);
},
),
),
);
}
}
Upvotes: 2