【问题标题】:Flutter - Update view on GestureDetector TapFlutter - 更新 GestureDetector Tap 上的视图
【发布时间】:2017-10-19 16:13:34
【问题描述】:

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

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

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

    您可能还想查看FlatButtonInkWell,以了解更多捕捉触摸的物质方式。如果您真的想要 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,
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

    • 是的,问题是我没有在我的构建函数中使用它,而是将它放在一个变量中......谢谢
    • 是的,通常最好在 build() 中创建小部件而不是存储它们。
    猜你喜欢
    • 2021-02-24
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2020-05-04
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多