Flutter - 在 GestureDetector Tap 上更新视图

Flutter - Update view on GestureDetector Tap

我正在尝试使用 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。否则我会创建一个颜色变量。有什么建议吗?

您可以使用 setState() inside of onTap. 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).

您可能还想查看 FlatButton or InkWell as more material-y ways to capture touches. If you really want a GestureDetector, read up on 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,
          ),
        ),
      ),
    );
  }
}