如何禁用 Flutter 中的按钮?

How do I disable a Button in Flutter?

我刚刚开始掌握 Flutter 的窍门,但我无法弄清楚如何设置按钮的启用状态。

在文档中,它说将 onPressed 设置为 null 以禁用按钮,并给它一个值以启用它。如果按钮在生命周期内继续处于相同状态,这很好。

我觉得我需要创建一个自定义有状态小部件,它允许我以某种方式更新按钮的启用状态(或 onPressed 回调)。

所以我的问题是我该怎么做?这似乎是一个非常简单的要求,但我在文档中找不到任何关于如何做到这一点的内容。

谢谢。

我想您可能想为 build 您的按钮和状态小部件引入一些辅助函数以及一些 属性 来启动。

  • 使用 StatefulWidget/State 并创建一个变量来保存您的条件(例如 isButtonDisabled
  • 最初将此设置为 true(如果这是您想要的)
  • 渲染按钮时,不要直接将 onPressed 值设置为 null 或某些函数 onPressed: () {}
  • 而不是,使用三元或辅助函数有条件地设置它(下面的示例)
  • 检查 isButtonDisabled 作为此条件的一部分,并 return null 或某些函数。
  • 按下按钮时(或任何时候你想禁用按钮)使用setState(() => isButtonDisabled = true)翻转条件变量。
  • Flutter 将使用新状态再次调用 build() 方法,按钮将使用 null 按下处理程序呈现并被禁用。

这是使用 Flutter 计数器项目的更多上下文。

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  bool _isButtonDisabled;

  @override
  void initState() {
    _isButtonDisabled = false;
  }

  void _incrementCounter() {
    setState(() {
      _isButtonDisabled = true;
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("The App"),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              'You have pushed the button this many times:',
            ),
            new Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
            _buildCounterButton(),
          ],
        ),
      ),
    );
  }

  Widget _buildCounterButton() {
    return new RaisedButton(
      child: new Text(
        _isButtonDisabled ? "Hold on..." : "Increment"
      ),
      onPressed: _isButtonDisabled ? null : _incrementCounter,
    );
  }
}

在这个例子中,我使用内联三元有条件地设置 TextonPressed,但将其提取到函数中可能更适合您(您可以使用相同的也可以更改按钮文本的方法):

Widget _buildCounterButton() {
    return new RaisedButton(
      child: new Text(
        _isButtonDisabled ? "Hold on..." : "Increment"
      ),
      onPressed: _counterButtonPress(),
    );
  }

  Function _counterButtonPress() {
    if (_isButtonDisabled) {
      return null;
    } else {
      return () {
        // do anything else you may want to here
        _incrementCounter();
      };
    }
  }

根据 docs:

If the onPressed callback is null, then the button will be disabled and by default will resemble a flat button in the disabledColor.

所以,您可以这样做:

RaisedButton(
  onPressed: calculateWhetherDisabledReturnsBool() ? null : () => whatToDoOnPressed,
  child: Text('Button text')
);

简单的答案是 onPressed : null 给出了一个禁用的按钮。

对于特定且有限数量的小部件,将它们包装在小部件 IgnorePointer 中正是这样做的:当其 ignoring 属性 设置为 true 时,子小部件 (实际上,整个子树)是不可点击的。

IgnorePointer(
    ignoring: true, // or false
    child: RaisedButton(
        onPressed: _logInWithFacebook,
        child: Text("Facebook sign-in"),
        ),
),

否则,如果您打算禁用整个子树,请查看 AbsorbPointer()。

禁用点击:

onPressed: null

启用点击:

onPressed: () => fooFunction() 
// or
onPressed: fooFunction

组合:

onPressed: shouldEnable ? fooFunction : null

你也可以使用AbsorbPointer,使用方法如下:

AbsorbPointer(
      absorbing: true, // by default is true
      child: RaisedButton(
        onPressed: (){
          print('pending to implement onPressed function');
        },
        child: Text("Button Click!!!"),
      ),
    ),

如果你想了解更多关于这个插件的信息,可以查看下面的linkFlutter Docs

大多数小部件的启用和禁用功能相同。

例如,按钮、开关、复选框等

只需设置 onPressed 属性 如下图

onPressed : null returns 禁用小部件

onPressed : (){}onPressed : _functionName returns 启用小部件

这是我认为最简单的方法:

RaisedButton(
  child: Text("PRESS BUTTON"),
  onPressed: booleanCondition
    ? () => myTapCallback()
    : null
)

您也可以设置空白条件,代替设置空值

         var isDisable=true;

   

          RaisedButton(
              padding: const EdgeInsets.all(20),
              textColor: Colors.white,
              color: Colors.green,
              onPressed:  isDisable
                  ? () => (){} : myClickingData(),
              child: Text('Button'),
            )

我喜欢为此使用 flutter_mobx 并在状态上工作。

接下来我使用观察者:

Container(child: Observer(builder: (_) {
  var method;
  if (!controller.isDisabledButton) method = controller.methodController;
  return RaiseButton(child: Text('Test') onPressed: method);
}));

在控制器上:

@observable
bool isDisabledButton = true;

然后在控件中你可以随意操作这个变量。

参考:Flutter mobx

用于禁用 flutter 中的任何 Button,例如 FlatButtonRaisedButtonMaterialButtonIconButton 等所有你需要的要做的是将 onPressedonLongPress 属性设置为 null。以下是一些按钮的简单示例:

平面按钮(启用)

FlatButton(
  onPressed: (){}, 
  onLongPress: null, // Set one as NOT null is enough to enable the button
  textColor: Colors.black,
  disabledColor: Colors.orange,
  disabledTextColor: Colors.white,
  child: Text('Flat Button'),
),

平面按钮(禁用)

FlatButton(
  onPressed: null,
  onLongPress: null,
  textColor: Colors.black,
  disabledColor: Colors.orange,
  disabledTextColor: Colors.white,
  child: Text('Flat Button'),
),

RaisedButton(启用)

RaisedButton(
  onPressed: (){},
  onLongPress: null, // Set one as NOT null is enough to enable the button
  // For when the button is enabled
  color: Colors.lightBlueAccent,
  textColor: Colors.black,
  splashColor: Colors.blue,
  elevation: 8.0,

  // For when the button is disabled
  disabledTextColor: Colors.white,
  disabledColor: Colors.orange,
  disabledElevation: 0.0,

  child: Text('Raised Button'),
),

RaisedButton(禁用)

RaisedButton(
  onPressed: null,
  onLongPress: null,
  // For when the button is enabled
  color: Colors.lightBlueAccent,
  textColor: Colors.black,
  splashColor: Colors.blue,
  elevation: 8.0,

  // For when the button is disabled
  disabledTextColor: Colors.white,
  disabledColor: Colors.orange,
  disabledElevation: 0.0,

  child: Text('Raised Button'),
),

图标按钮(启用)

IconButton(
  onPressed: () {},
  icon: Icon(Icons.card_giftcard_rounded),
  color: Colors.lightBlueAccent,
            
  disabledColor: Colors.orange,
),

图标按钮(禁用)

IconButton(
  onPressed: null,
  icon: Icon(Icons.card_giftcard_rounded),
  color: Colors.lightBlueAccent,
            
  disabledColor: Colors.orange,
),

注意: 一些按钮如IconButton只有onPressed 属性.

此答案基于 Flutter 2.x

的更新按钮 TextButton/ElevatedButton/OutlinedButton

不过,按钮的启用或禁用基于 onPressed 属性。如果 属性 为空,则按钮将被禁用。如果您将功能分配给 onPressed,那么按钮将被启用。 在下面的片段中,我展示了如何 enable/disable 按钮并相应地更新它的样式。

This post also indicating that how to apply different styles to new Flutter 2.x buttons.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool textBtnswitchState = true;
  bool elevatedBtnSwitchState = true;
  bool outlinedBtnState = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  child: Text('Text Button'),
                  onPressed: textBtnswitchState ? () {} : null,
                  style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.resolveWith(
                      (states) {
                        if (states.contains(MaterialState.disabled)) {
                          return Colors.grey;
                        } else {
                          return Colors.red;
                        }
                      },
                    ),
                  ),
                ),
                Column(
                  children: [
                    Text('Change State'),
                    Switch(
                      value: textBtnswitchState,
                      onChanged: (newState) {
                        setState(() {
                          textBtnswitchState = !textBtnswitchState;
                        });
                      },
                    ),
                  ],
                )
              ],
            ),
            Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ElevatedButton(
                  child: Text('Text Button'),
                  onPressed: elevatedBtnSwitchState ? () {} : null,
                  style: ButtonStyle(
                    foregroundColor: MaterialStateProperty.resolveWith(
                      (states) {
                        if (states.contains(MaterialState.disabled)) {
                          return Colors.grey;
                        } else {
                          return Colors.white;
                        }
                      },
                    ),
                  ),
                ),
                Column(
                  children: [
                    Text('Change State'),
                    Switch(
                      value: elevatedBtnSwitchState,
                      onChanged: (newState) {
                        setState(() {
                          elevatedBtnSwitchState = !elevatedBtnSwitchState;
                        });
                      },
                    ),
                  ],
                )
              ],
            ),
            Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                OutlinedButton(
                  child: Text('Outlined Button'),
                  onPressed: outlinedBtnState ? () {} : null,
                  style: ButtonStyle(
                      foregroundColor: MaterialStateProperty.resolveWith(
                    (states) {
                      if (states.contains(MaterialState.disabled)) {
                        return Colors.grey;
                      } else {
                        return Colors.red;
                      }
                    },
                  ), side: MaterialStateProperty.resolveWith((states) {
                    if (states.contains(MaterialState.disabled)) {
                      return BorderSide(color: Colors.grey);
                    } else {
                      return BorderSide(color: Colors.red);
                    }
                  })),
                ),
                Column(
                  children: [
                    Text('Change State'),
                    Switch(
                      value: outlinedBtnState,
                      onChanged: (newState) {
                        setState(() {
                          outlinedBtnState = !outlinedBtnState;
                        });
                      },
                    ),
                  ],
                )
              ],
            ),
          ],
        ),
      ),
    );
  }
}

如果您正在寻找一种快速的方法并且不关心让用户实际点击按钮的次数超过一次。您也可以通过以下方式进行:

// Constant whether button is clicked
bool isClicked = false;

然后在 onPressed() 函数中检查用户是否已经单击了按钮。

onPressed: () async {
    if (!isClicked) {
       isClicked = true;
       // await Your normal function
    } else {
       Toast.show(
          "You click already on this button", context,
          duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
    }
}

您可以在您的应用程序中使用此代码来加载和禁用按钮:

class BtnPrimary extends StatelessWidget {
  bool loading;
  String label;
  VoidCallback onPressed;

  BtnPrimary(
      {required this.label, required this.onPressed, this.loading = false});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton.icon(
      icon: loading
          ? const SizedBox(
              child: CircularProgressIndicator(
                color: Colors.white,
              ),
              width: 20,
              height: 20)
          : const SizedBox(width: 0, height: 0),
      label: loading ? const Text('Waiting...'): Text(label),
      onPressed: loading ? null : onPressed,
    );
  }
}

希望有用

在 Flutter 中禁用按钮的最简单方法是将 null 值分配给 onPressed

ElevatedButton(
  style: ElevatedButton.styleFrom(
    primary: Colors.blue, // background
    onPrimary: Colors.white, // foreground
  ),
  onPressed: null,
  child: Text('ElevatedButton'),
),