I have an elevated button, to which i want to disable it after user hits the button, api gets called here. i have tried to setState but itseems not working. what else can i do to disable button.
hint: my concept i am working is that once ther users clicks the button, again the user should not be able to click again the same button.
Here is my code:
bool isEnable = false;
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
const Color.fromARGB(255, 53, 121, 87)),
padding:
MaterialStateProperty.all(const EdgeInsets.all(20)),
textStyle: MaterialStateProperty.all(const TextStyle(
fontSize: 14, color: Colors.black))),
onPressed: qrdata.code != 9 && !isEnable
? () async {
setState(() {
isEnable = true;
});
var url = Uri.parse(
'${ApiConstants.baseUrl}${ApiConstants.updateEndpoint}');
var responseData = await http.put(url,
headers: ApiConstants.headers);
if (responseData.statusCode == 202) {
print(jsonDecode(responseData.body).toString());
// ignore: use_build_context_synchronously
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Dashboard(
data: widget.data,
)),
);
}
//FocusManager.instance.primaryFocus!.unfocus();
// });
// setState(() {
// isEnable = false;
// });
}
:null,
// : () {},
icon: const Icon(
Icons.home_filled,
),
label: const Text('Entry',
style: TextStyle(
color: Colors.white,
)),
),
2
Answers
Apply this code bellow:
You got error on double equal.
bool variable:
Widget
Please make sure variable
qrdata.code
andisEnable
are initialized outside the build method. Every time when setState is called one or both the variables are getting reset.The problem is whenever setState is pressed it is not rebuilding the button state. so to change the button state wrap your button with StatefulBuilder.
and please call your API in
try catch
.The problem in your code is setting
isEnable
to true but not resting to false.