我正在尝试使用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,
),
),
Run Code Online (Sandbox Code Playgroud)
问题是我不能在onTap中使用setState。否则我会创建一个颜色变量。有什么建议么?
您可以setState()
在中使用onTap
。实际上,在这种情况下这确实是正确的事情。如果您在调用时遇到问题setState()
,请确保您的小部件是有状态的(请参阅交互性教程)。
您可能还想签出FlatButton
或InkWell
更重要的方式来捕获触摸。如果您确实需要GestureDetector
,请继续阅读HitTestBehavior
以确保正确配置它。
这是一个示例,每次单击时都会变为随机颜色。
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,
),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4903 次 |
最近记录: |