我刚开始掌握Flutter的窍门,但我不知道如何设置按钮的启用状态。
从文档中,它说将onPressed设置为null来禁用按钮,并给它一个值来启用它。如果按钮在生命周期中继续处于相同的状态,这是没问题的。
我得到的印象是,我需要创建一个自定义的有状态小部件,它将允许我以某种方式更新按钮的启用状态(或onPressed回调)。
我的问题是我该怎么做?这似乎是一个非常简单的要求,但我在文档中找不到任何关于如何做到这一点的东西。
谢谢。
我刚开始掌握Flutter的窍门,但我不知道如何设置按钮的启用状态。
从文档中,它说将onPressed设置为null来禁用按钮,并给它一个值来启用它。如果按钮在生命周期中继续处于相同的状态,这是没问题的。
我得到的印象是,我需要创建一个自定义的有状态小部件,它将允许我以某种方式更新按钮的启用状态(或onPressed回调)。
我的问题是我该怎么做?这似乎是一个非常简单的要求,但我在文档中找不到任何关于如何做到这一点的东西。
谢谢。
当前回答
你也可以设置空白条件,在设置null的地方
var isDisable=true;
RaisedButton(
padding: const EdgeInsets.all(20),
textColor: Colors.white,
color: Colors.green,
onPressed: isDisable
? () => (){} : myClickingData(),
child: Text('Button'),
)
其他回答
有两种方法:
1- https://stackoverflow.com/a/49354576/5499531
2-你可以使用MaterialStatesController:
final _statesController = MaterialStatesController();
然后将状态更改为:
_statesController.update(
MaterialState.disabled,
true, // or false depending on your logic
);
在你的按钮上
ElevatedButton(
onPressed: _onPressed,
statesController: _statesController,
child: Text("Awesome"),
),
此外,你可以改变按钮的风格,当禁用: 在主题设置中:
....
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
backgroundColor: colors.primary500, // set your own color
textStyle: button, // set your own style
onPrimary: colors.onPrimary100, // set your own color
enableFeedback: true,
disabledBackgroundColor: colors.primary300, // set your own color
disabledForegroundColor: colors.primary300, // set your own color
disabledMouseCursor: SystemMouseCursors.forbidden, // when is disable the change the cursor type
),
),
...
大多数小部件的启用和禁用功能是相同的。
前,按钮,开关,复选框等。
只需设置onPressed属性,如下所示
onPressed: null返回禁用小部件
onPressed:(){}或onPressed: _functionName返回启用的小部件
你也可以使用吸收指针,你可以用下面的方式使用它:
AbsorbPointer(
absorbing: true, // by default is true
child: RaisedButton(
onPressed: (){
print('pending to implement onPressed function');
},
child: Text("Button Click!!!"),
),
),
如果您想了解有关此小部件的更多信息,可以查看以下链接Flutter Docs
见下面的可能的解决方案,添加'ValueListenableBuilder'的'TextEditingValue'监听控制器(TextEditingController),并返回你的函数调用如果控制器。文本不为空,如果为空则返回'null'。
// valuelistenablebuilder环绕按钮
ValueListenableBuilder<TextEditingValue>(
valueListenable: textFieldController,
builder: (context, ctrl, __) => ElevatedButton(
onPressed: ctrl.text.isNotEmpty ? yourFunctionCall : null,
child: Text(
'SUBMIT',
style: GoogleFonts.roboto(fontSize: 20.0),
),
),
),
特克斯菲尔德
TextField(controller: textFieldController,
onChanged: (newValue) {
textFieldText = newValue;
},
),
生成器将监听控制器,并仅在使用文本字段时启用按钮。我希望这能回答问题。让我知道…
禁用点击:
onPressed: null
可以点击:
onPressed: () => fooFunction()
// or
onPressed: fooFunction
组合:
onPressed: shouldEnable ? fooFunction : null