我尝试使用下面的代码添加一个简单的显示,显示我预先加载到模型对象中的列表中的所有表情符号。但是,当我在Web输出中运行此代码时,对于添加的每个GestureDetector,都会立即调用onTap侦听器。我不知道为什么?
class EmojiKeyboard extends StatefulWidget {
EmojiKeyboard();
@override
State<StatefulWidget> createState() => _EmojiKeyboardState();
}
class _EmojiKeyboardState extends State<EmojiKeyboard> {
@override
void initState() {
super.initState();
}
_emojiTapped(String emoji) {
print(emoji);
}
@override
Widget build(BuildContext context) {
//i load the list of emoji from a model object in my real code, simplifying here to not distract from the issue
List<String> listEmoji = [];
List<Column> columns = [];
List<Widget> children = [];
for (int i = 0; i < listEmoji.length; i++) {
var emoji = listEmoji[i];
children.add(GestureDetector(
child: Text("${emoji}",
style: TextStyle(
decoration: TextDecoration.none,
fontSize: 36,
fontFamily: Emoji.getFontNameForPlatform())),
onTap: _emojiTapped("$emoji"))
);
if (i % 4 == 0) {
columns.add(Column(
children: children,
));
children = [];
}
}
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: columns,
));
}
}
1条答案
按热度按时间hgc7kmma1#
您没有正确地将函数传递给
onTap
。您当前正在执行的操作是调用_emojiTapped("$emoji")
并将其返回值传递给onTap
。您需要创建一个匿名函数传递给onTap
,然后onTap
调用_emojiTapped
。