在长按时在Flutter上显示某物。

huangapple go评论66阅读模式
英文:

show something on long press flutter

问题

我想点击一个按钮,当我按住它时,在屏幕上显示一些东西。当我离开按钮时,我希望它消失或恢复到第一个位置,就像在我按下按钮之前一样。我尝试使用布尔标志和WhenTapDwon和WhenTapUp选项来实现,但没有成功。

import 'dart:math';

import 'package:flutter/material.dart';
import 'Screen building third test.dart';
import 'globals.dart' as globals;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
    );
  }
}

class LBulb extends StatefulWidget {
  const LBulb({super.key});

  @override
  State<LBulb> createState() => _LBulb();
}

final stopwatchD = Stopwatch();
final stopwatchR = Stopwatch();
bool chosen1 = false;
bool chosen2 = false;
bool chosen3 = false;
bool chosen4 = false;
bool chosen5 = false;
bool chosen6 = false;
bool chosen7 = false;
bool chosen8 = false;
int ver = 0;
List<int> lightsIndex = [];

class _LBulb extends State<LBulb> {
  @override
  void initState() {
    ver = oneOrThree();
    lightsIndex = randomLights(ver);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print(lightsIndex);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue[600]?.withOpacity(0.5),
      ),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("assets/images/background2.png"),
              fit: BoxFit.cover),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(height: 60),
            const Text(
              "Please click on the appropriate light's button",
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: Colors.black,
                  fontSize: 40,
                  fontWeight: FontWeight.bold,
                  fontFamily: 'Alkatra'),
            ),
            const SizedBox(height: 30),
            Center(
              child: Container(
                height: 500,
                width: 810,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(100),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.5),
                      offset: const Offset(
                        7.0,
                        7.0,
                      ),
                      blurRadius: 10.0,
                    ),
                  ],
                ),
                child: screenBuilding(
                  distance: 310.0,
                  // Center button
                  centerButton: TextButton(
                    onPressed: () {},
                    child: Container(
                      height: 20,
                      width: 20,
                      decoration: BoxDecoration(
                          color: Colors.black,
                          borderRadius: BorderRadius.circular(500)),
                      child: GestureDetector(
                        // while long tap
                        onTapDown: (details) {
                          // start the detection timer
                          stopwatchD.start();
                          // chose the number and index of the lights that will be turned
                          for (int i = 0; i < lightsIndex.length; i++) {
                            if (lightsIndex[i] == 1) {
                              chosen1 = true;
                            }
                            if (lightsIndex[i] == 2) {
                              chosen2 = true;
                            }
                            if (lightsIndex[i] == 3) {
                              chosen3 = true;
                            }
                            if (lightsIndex[i] == 4) {
                              chosen4 = true;
                            }
                            if (lightsIndex[i] == 5) {
                              chosen5 = true;
                            }
                            if (lightsIndex[i] == 6) {
                              chosen6 = true;
                            }
                            if (lightsIndex[i] == 7) {
                              chosen7 = true;
                            }
                            if (lightsIndex[i] == 8) {
                              chosen8 = true;
                            }
                          }
                        },
                        // when the player releases the button
                        onTapUp: (details) {
                          // save the time of the detection time
                          stopwatchD.stop();
                          globals.detectionTime = stopwatchD.elapsed;
                          globals.detectionTimes[globals.numOfTurn] =
                              globals.detectionTime;
                          // reset the values
                          stopwatchD.reset();
                          globals.detectionTime = const Duration(seconds: 0);
                          globals.numOfTurn++;
                          print(globals.detectionTimes);
                          // update lights
                          stopwatchR.start();
                        },
                      ),
                    ),
                  ),
                  // the lights buttons
                  buttonsFirstRow: [
                    TextButton(
                      onPressed: () {
                        print("clicked1");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        print("clicked2");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        print("clicked3");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        print("clicked4");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        print("clicked5");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        print("clicked6");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        print("clicked7");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                    TextButton(
                      onPressed: () {
                        print("clicked8");
                      },
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.black,
                            borderRadius: BorderRadius.circular(500)),
                      ),
                    ),
                  ],
                  // the first 4 lights
                  buttonsSecondRowHalf1: [
                    TextButton(
                      onPressed: () {},
                      child: Container(
                        height: 20,
                        width: 20,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(500),
                           

<details>
<summary>英文:</summary>

i want to click a button and while i am pressing it to show something on the screen. When i leave the button i want to make it disapear or change it back to the first place, like it was before i pressed the button. 
I tried to make it with boolean flags and with the options of WhenTapDwon and WhenTapUp but it didnt work 

    import &#39;dart:math&#39;;
    
    import &#39;package:flutter/material.dart&#39;;
    import &#39;Screen building third test.dart&#39;;
    import &#39;globals.dart&#39; as globals;
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          debugShowCheckedModeBanner: false,
        );
      }
    }
    
    class LBulb extends StatefulWidget {
      const LBulb({super.key});
    
      @override
      State&lt;LBulb&gt; createState() =&gt; _LBulb();
    }
    
    final stopwatchD = Stopwatch();
    final stopwatchR = Stopwatch();
    bool chosen1 = false;
    bool chosen2 = false;
    bool chosen3 = false;
    bool chosen4 = false;
    bool chosen5 = false;
    bool chosen6 = false;
    bool chosen7 = false;
    bool chosen8 = false;
    int ver = 0;
    List&lt;int&gt; lightsIndex = [];
    
    class _LBulb extends State&lt;LBulb&gt; {
      @override
      void initState() {
        ver = oneOrThree();
        lightsIndex = randomLights(ver);
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        print(lightsIndex);
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.blue[600]?.withOpacity(0.5),
          ),
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(&quot;assets/images/background2.png&quot;),
                  fit: BoxFit.cover),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 60),
                const Text(
                  &quot;Please click on the appropriate light&#39;s button&quot;,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: 40,
                      fontWeight: FontWeight.bold,
                      fontFamily: &#39;Alkatra&#39;),
                ),
                const SizedBox(height: 30),
                Center(
                  child: Container(
                    height: 500,
                    width: 810,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(100),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.5),
                          offset: const Offset(
                            7.0,
                            7.0,
                          ),
                          blurRadius: 10.0,
                        ),
                      ],
                    ),
                    child: screenBuilding(
                      distance: 310.0,
                      // Center button
                      centerButton: TextButton(
                        onPressed: () {},
                        child: Container(
                          height: 20,
                          width: 20,
                          decoration: BoxDecoration(
                              color: Colors.black,
                              borderRadius: BorderRadius.circular(500)),
                          child: GestureDetector(
                            // while long tap
                            onTapDown: (details) {
                              // start the detection timer
                              stopwatchD.start();
                              // chose the number and index of the lights that will be turned
                              for (int i = 0; i &lt; lightsIndex.length; i++) {
                                if (lightsIndex[i] == 1) {
                                  chosen1 = true;
                                }
                                if (lightsIndex[i] == 2) {
                                  chosen2 = true;
                                }
                                if (lightsIndex[i] == 3) {
                                  chosen3 = true;
                                }
                                if (lightsIndex[i] == 4) {
                                  chosen4 = true;
                                }
                                if (lightsIndex[i] == 5) {
                                  chosen5 = true;
                                }
                                if (lightsIndex[i] == 6) {
                                  chosen6 = true;
                                }
                                if (lightsIndex[i] == 7) {
                                  chosen7 = true;
                                }
                                if (lightsIndex[i] == 8) {
                                  chosen8 = true;
                                }
                              }
                            },
                            // when the player release the button
                            onTapUp: (details) {
                              // save the time of the detection time
                              stopwatchD.stop();
                              globals.detectionTime = stopwatchD.elapsed;
                              globals.detectionTimes[globals.numOfTurn] =
                                  globals.detectionTime;
                              // reset the values
                              stopwatchD.reset();
                              globals.detectionTime = const Duration(seconds: 0);
                              globals.numOfTurn++;
                              print(globals.detectionTimes);
                              // update lights
                              stopwatchR.start();
                            },
                          ),
                        ),
                      ),
                      // the lights buttons
                      buttonsFirstRow: [
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked1&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked2&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked3&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked4&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked5&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked6&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked7&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {
                            print(&quot;clicked8&quot;);
                          },
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.black,
                                borderRadius: BorderRadius.circular(500)),
                          ),
                        ),
                      ],
                      // the first 4 light
                      buttonsSecondRowHalf1: [
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                      ],
                      // the other 4 light
                      buttonsSecondRowHalf2: [
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                        TextButton(
                          onPressed: () {},
                          child: Container(
                            height: 20,
                            width: 20,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(500),
                                border: Border.all(width: 3)),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      }
    
      int oneOrThree() {
        final rand = Random();
        List&lt;int&gt; a = [1, 3];
        return a[rand.nextInt(a.length)];
      }
    
      List&lt;int&gt; randomLights(int ver) {
        final rand = Random();
        List&lt;int&gt; a = [1, 2, 3, 4, 5, 6, 7, 8];
        List&lt;int&gt; ans = [];
        if (ver == 1) {
          int temp = a[rand.nextInt(a.length)];
          ans.add(temp);
        } else {
          int temp1 = a[rand.nextInt(a.length)];
          a.remove(temp1);
          ans.add(temp1);
          int temp2 = a[rand.nextInt(a.length)];
          a.remove(temp2);
          ans.add(temp2);
          int temp3 = a[rand.nextInt(a.length)];
          ans.add(temp3);
        }
        return ans;
      }
    }



</details>


# 答案1
**得分**: 1

你可以在`GestureDetector`小部件上使用`onLongPress`和`onLongPressEnd`来实现它。

```dart
GestureDetector(
  onLongPress: () {
    setState(() {
      _isLongPressActivated = true;
    });
  },
  onLongPressEnd: (details) {
    setState(() {
      _isLongPressActivated = false;
    });
  },

我已经添加了下面的示例代码。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Long Press Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyLongPressWidget(),
    );
  }
}

class MyLongPressWidget extends StatefulWidget {
  @override
  _MyLongPressWidgetState createState() => _MyLongPressWidgetState();
}

class _MyLongPressWidgetState extends State<MyLongPressWidget> {
  bool _isLongPressActivated = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPress: () {
        setState(() {
          _isLongPressActivated = true;
        });
      },
      onLongPressEnd: (details) {
        setState(() {
          _isLongPressActivated = false;
        });
      },
      child: Scaffold(
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: 200,
              height: 200,
              color: _isLongPressActivated ? Colors.blue : Colors.red,
              child: Center(
                child: Text(
                  _isLongPressActivated
                      ? 'Long Press Activated'
                      : 'Long Press to Activate',
                  style: TextStyle(fontSize: 16.0, color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

尝试类似这样的东西。

英文:

You can use onLongPress and onLongPressEnd on GestureDetector widget to achieve it.

GestureDetector(
onLongPress: () {
setState(() {
_isLongPressActivated = true;
});
},
onLongPressEnd: (details) {
setState(() {
_isLongPressActivated = false;
});
},

i have add sample code below

import &#39;package:flutter/material.dart&#39;;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: &#39;Long Press Example&#39;,
theme: ThemeData(primarySwatch: Colors.blue),
home: MyLongPressWidget(),
);
}
}
class MyLongPressWidget extends StatefulWidget {
@override
_MyLongPressWidgetState createState() =&gt; _MyLongPressWidgetState();
}
class _MyLongPressWidgetState extends State&lt;MyLongPressWidget&gt; {
bool _isLongPressActivated = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onLongPress: () {
setState(() {
_isLongPressActivated = true;
});
},
onLongPressEnd: (details) {
setState(() {
_isLongPressActivated = false;
});
},
child: Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 200,
height: 200,
color: _isLongPressActivated ? Colors.blue : Colors.red,
child: Center(
child: Text(
_isLongPressActivated
? &#39;Long Press Activated&#39;
: &#39;Long Press to Activate&#39;,
style: TextStyle(fontSize: 16.0, color: Colors.white),
),
),
),
],
),
),
);
}
}

try something like this

huangapple
  • 本文由 发表于 2023年6月5日 18:38:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定