[英]Flutter - Update view on GestureDetector Tap
I am trying to change the color of the element the user clicked on using a GestureDetector: 我正在尝试使用GestureDetector更改用户单击的元素的颜色:
new GestureDetector(
onTap: (){
// Change the color of the container beneath
},
child: new Container(
width: 80.0,
height: 80.0,
margin: new EdgeInsets.all(10.0),
color: Colors.orange,
),
),
The problem is that I can't use setState inside of onTap. 问题是我不能在onTap中使用setState。 Otherwise I would have created a color variable.
否则我会创建一个颜色变量。 Any suggestions?
有什么建议?
You can use setState()
inside of onTap
. 您可以在
onTap
使用setState()
。 In fact, that's exactly the right thing to do in this situation. 事实上,在这种情况下,这是正确的做法。 If you are having trouble calling
setState()
, make sure your widget is stateful (see the interactivity tutorial ). 如果您在调用
setState()
遇到问题,请确保您的窗口小部件是有状态的(请参阅交互性教程 )。
You might also want to check out FlatButton
or InkWell
as more material-y ways to capture touches. 您可能还想查看
FlatButton
或InkWell
作为捕获触摸的更多材料。 If you really want a GestureDetector
, read up on HitTestBehavior
to make sure you're configuring it correctly. 如果你真的想要一个
GestureDetector
,请阅读HitTestBehavior
以确保你正确配置它。
Here's an example that changes to a random color every time it's clicked. 这是一个每次点击时都会变为随机颜色的示例。
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHome(),
);
}
}
class MyHome extends StatefulWidget {
@override
State createState() => new _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
final Random _random = new Random();
Color _color = Colors.orange;
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new GestureDetector(
onTap: () {
// Change the color of the container beneath
setState(() {
_color = new Color.fromRGBO(
_random.nextInt(256),
_random.nextInt(256),
_random.nextInt(256),
1.0
);
});
},
child: new Container(
width: 80.0,
height: 80.0,
margin: new EdgeInsets.all(10.0),
color: _color,
),
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.