flutter 如何在一段时间内禁用升高按钮?

axr492tv  于 2022-12-30  发布在  Flutter
关注(0)|答案(2)|浏览(221)

我想禁用一个按钮900ms(使用抖动)。我该怎么做?

if (isButtonDisabled == false) {
                                    incrementCounter();
                                    AudioPlayer().play(
                                        AssetSource(
                                            Assets.correct_answer_audio),
                                        volume: 1.0);
                                    _onTyping();
                                  
                                    await Future.delayed(
                                        const Duration(milliseconds: 900));
                                    Navigator.of(context).pop();
                                    );
                                  }
jljoyd4f

jljoyd4f1#

要禁用ElevatedButton,您需要在应该禁用null时将其设置为onPressed。然后通过Future.delayedTimer启用它,方法是将enabled变量设置为true并调用setState。您可以在Dartpad中检查此代码片段。

import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: MyStatefulWidget(),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});
  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  bool enabled = false;

  @override
  initState() {
    super.initState();
    Timer(
        const Duration(seconds: 3),
        () => setState(() {
              enabled = true;
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Center(
        child: ElevatedButton(
            onPressed: enabled ? () {} : null,
            child: Text('Button is ${enabled ? 'enabled' : 'disabled'}')));
  }
}
mwecs4sa

mwecs4sa2#

  • 对于Disabled Button =〉onPressed : null
  • 对于Active Button =〉onPressed : (){}

在一定间隔后使用Timer,将isDisabledButton设置为false,默认情况下为true
示例:

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

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool isButtonDisabled = true;
  @override
  void initState() {
    Timer(
        const Duration(seconds: 2),
        () => setState(() {
              isButtonDisabled = false;
            }));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: const Text(
          "Home Page",
        ),
        backgroundColor: Colors.transparent,
      ),
      body: Center(
          child: FilledButton(
              onPressed: isButtonDisabled ? null : () {},
              child: const Text("Disable Button"))),
    );
  }
}
前2秒:

2秒后:

相关问题