我有一个类RedditArtReward
,它将一个tapphandler传递给另一个类RedditPixels
。RedditArtReward
实现如下:
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
实施如下:
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)),
)),
);
},
),
]
],
)
]),
]));
}
}
在onTap
中,我想传递i和j的值,以找出单击了哪个元素。有没有办法将这些值从onTap
传递到handleTap
函数?我尝试将final VoidCallback tapHandler;
替换为使用Function(int, int)
,但失败并出现错误。
生成LayoutBuilder时引发了以下Assert:在构建期间调用了setState()或NeedmarksBuild()。
1条答案
按热度按时间y1aodyip1#
对于传递值,函数将为
调用这个函数
以及
RedditArtReward
上的用例此外,您可能更喜欢命名参数而不是位置参数。