I have a class RedditArtReward that passes a taphandler to another class RedditPixels. RedditArtReward implementation below:
class RedditArtReward extends StatefulWidget {
const RedditArtReward({super.key});
@override
State<RedditArtReward> createState() => _RedditArtRewardState();
}
class _RedditArtRewardState extends State<RedditArtReward> {
int matrixSize = 9;
late List<List<Color>> pixelColorMatrix = getAlmostRandomMatrix(matrixSize);
// this function is used to generate a random size x size matrix with 3 colors
getAlmostRandomMatrix(size) {
makeMatrix() => Iterable<List<Color>>.generate(
size, (i) => List<Color>.filled(size, Colors.red)).toList();
List<List<Color>> matrix =
makeMatrix(); //size x size matrix with red default
return matrix;
}
void handleTap() {
setState(() {
pixelColorMatrix[0][0] = Colors.transparent;
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Scaffold(
backgroundColor: Colors.transparent,
body: Padding(
padding:
const EdgeInsets.only(left: 10, top: 80, right: 10, bottom: 0),
child: Column(
children: [
RedditPixels(pixelColorMatrix, matrixSize, handleTap),
],
),
),
),
);
}
}
RedditPixels implementation below:
class RedditPixels extends StatelessWidget {
final List<List<Color>> matrix;
final int size;
final VoidCallback tapHandler;
const RedditPixels(this.matrix, this.size, this.tapHandler, {super.key});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(8.0),
child: Stack(children: <Widget>[
Column(children: [
for (int i = 0; i < size; i++)
Row(
children: [
for (int j = 0; j < size; j++) ...[
LayoutBuilder(
builder: (context, constraints) {
return Align(
alignment: Alignment.topLeft,
child: GestureDetector(
onTap: tapHandler,
child: Container(
width: 40,
height: 35,
decoration: BoxDecoration(
color: matrix[i][j],
border: Border.all(
width: 1, color: Colors.white)),
)),
);
},
),
]
],
)
]),
]));
}
}
In the onTap i want to pass the value of i and j to find out which element was clicked. is there a way to pass these values from the onTap to the handleTap function?
I tried replacing final VoidCallback tapHandler; to use Function(int, int) but failed with errors.
The following assertion was thrown building LayoutBuilder: setState()
or markNeedsBuild() called during build.
>Solution :
For passing value, the function will be
final Function(int i, int j) tapHandler;
And call this function
child: GestureDetector(
onTap: () => tapHandler(i, j),
And use case on RedditArtReward
RedditPixels(pixelColorMatrix, matrixSize, (i, j) {
setState(() {
pixelColorMatrix[i][j] = Colors.transparent;
});
}),
Also, you may prefer named argument instead of positional.