颤动 - 更新GestureDetector Tap的视图

时间:2017-05-19 13:39:34

标签: dart flutter

我正在尝试使用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,
    ),
  ),

问题是我无法在onTap中使用setState。否则我会创建一个颜色变量。有什么建议吗?

1 个答案:

答案 0 :(得分:4)

您可以在onTap内使用setState()。事实上,在这种情况下,这是正确的做法。如果您在调用setState()时遇到问题,请确保您的小部件是有状态的(请参阅interactivity tutorial)。

您可能还想查看FlatButtonInkWell作为捕获触摸的更多重要方法。如果您真的需要GestureDetector,请阅读HitTestBehavior以确保正确配置。

这是一个每次点击时都会变为随机颜色的示例。

screenshot

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,
          ),
        ),
      ),
    );
  }
}