How to update value in dialog flutter

  Update value in showDialog 


Today we discuss update value in showDialog. We StateFulWidget class and StateLess Widget class. We use the StateLess Widget class when we don't need to update the value in the UI and state of the app. In StateFulWidget class we are able to change the state of the app. 

With the help of showDialog, we were able to apply alert dialog and normal informative dialog. When we wrote the content in the dialog and add buttons, text, etc. we want to change and update the value in on-tap
in dialog, the value can't update because showDialog can't update the app state.


Let's get start



First, you need to add a showDialog in the app and initialize a variable and use it in the show dialog and add a button to update a value.


    showDialog(context: context, builder: (_){
      return Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Container(
          height: 300  ,
          child: Column(
            children: [
              const SizedBox(height: 10,),
           const   Text("Update Value",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 17),),
const SizedBox(height: 40,),
Text(_myValue.toString(),style:const TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
const SizedBox(height: 50,),
ElevatedButton(onPressed: (){
setState(() {
  _myValue++;
});
}, child: Text("Update Value"))
            ],
          ),
               ),
      );
    });




Now you click on the update value button to update the value.  the value not updated currently. when you close and open the dialog you see the updated value. 


For update value on click, you need to wrap dialog content with statefulbuilder and use statefulbuilder setState for update changes see the below code.



showDialog(context: context, builder: (_){
      return StatefulBuilder(
        builder: (context,setState2) {
          return Dialog(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            child: Container(
              height: 300  ,
              child: Column(
                children: [
                  const SizedBox(height: 10,),
               const   Text("Update Value",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 17),),
const SizedBox(height: 40,),
Text(_myValue.toString(),style:const TextStyle(fontSize: 20,fontWeight: FontWeight.w500),),
const SizedBox(height: 50,),
ElevatedButton(onPressed: (){
setState2(() {
  _myValue++;
});
}, child: Text("Update Value"))
                ],
              ),
                   ),
          );
        }
      );
    });

And you see that value update on click. StateFulBuilder updates the app state from the showDialog.


  For more information on widgets, packages and solutions dive into the flutterStuff

Post a Comment

Previous Post Next Post

Contact Form