Creo que es posible que desee introducir algunas funciones auxiliares en buildsu botón, así como un widget con estado junto con alguna propiedad para eliminar.
- Use un StatefulWidget / State y cree una variable para mantener su condición (por ejemplo
isButtonDisabled)
- Establezca esto en verdadero inicialmente (si eso es lo que desea)
- Al renderizar el botón, no establezca directamente el
onPressed valor en ninguna nullfunción o en algunaonPressed: () {}
- En su lugar , configúrelo condicionalmente usando una función ternaria o auxiliar (ejemplo a continuación)
- Marque
isButtonDisabledcomo parte de este condicional y devuelva nulluna función o alguna.
- Cuando se presiona el botón (o siempre que desee deshabilitar el botón) use
setState(() => isButtonDisabled = true)para invertir la variable condicional.
- Flutter volverá a llamar al
build()método con el nuevo estado y el botón se renderizará con un nullcontrolador de prensa y se desactivará.
Aquí hay más contexto usando el proyecto de contador 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,
);
}
}
En este ejemplo, estoy usando un ternario en línea para establecer condicionalmente el Texty onPressed, pero puede ser más apropiado que extraiga esto en una función (puede usar este mismo método para cambiar el texto del botón también):
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();
};
}
}