skip to Main Content

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


  1. Apply this code bellow:
    You got error on double equal.

    bool variable:

    bool isDisabled = false;
    

    Widget

          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 && !isDisabled 
                        ?  () async {   
                             setState(() {
                               isDisabled = 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,
                                        )),
                              );
                           
                            }
                            });
                             setState(() {
                             isDisabled = false;
                               });
                        }
                        :null,
    
    Login or Signup to reply.
  2. Please make sure variable qrdata.code and isEnable 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.

    enter image description here

    class DisableButton extends StatefulWidget {
      const DisableButton({Key? key}) : super(key: key);
    
      @override
      State<DisableButton> createState() => _DisableButtonState();
    }
    
    class _DisableButtonState extends State<DisableButton> {
      bool isEnable = false;
      int qrdata = 1;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: StatefulBuilder(
              builder:
                  (BuildContext context, void Function(void Function()) setState) {
                return 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 != 9 && !isEnable
                      ? () async {
                          setState(() {
                            isEnable = true;
                          });
                          print(">>>> Button is disabled");
                          try {
                            final data = await http.get(
                              Uri.parse(
                                  'https://jsonplaceholder.typicode.com/albums/1'),
                            );
    
                            if (!mounted) return;
    
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => NextPage(
                                  data: data.body.toString(),
                                ),
                              ),
                            );
    
                            print("Api Data >>>> $data.body");
                          } catch (e) {
                            print("Error While fetching data");
                          }
                          setState(() {
                            isEnable = false;
                          });
                          print(">>>> Button is enabled");
                        }
                      : null,
    
                  // : () {},
                  icon: const Icon(
                    Icons.home_filled,
                  ),
                  label: Text(isEnable ? "Disabled" : "Enabled",
                      style: const TextStyle(
                        color: Colors.white,
                      )),
                );
              },
            ),
          ),
        );
      }
    }
    
    class NextPage extends StatelessWidget {
      const NextPage({Key? key, required this.data}) : super(key: key);
      final String data;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Center(child: Text("Data : $data")),
        );
      }
    }
    

    The problem in your code is setting isEnable to true but not resting to 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(() {  <---- Uncomment this code.
                              //  isEnable = false;
                              //   });
                          }
                          :null,
                    
                     // : () {},
                      icon: const Icon(
                        Icons.home_filled,
                      ),
                      label: const Text('Entry',
                          style: TextStyle(
                            color: Colors.white,
                          )),
                    ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search