Home > Net >  How to reload the page when some changes made from API Call Flutter
How to reload the page when some changes made from API Call Flutter

Time:07-16

I am creating food ordering mobile application using Flutter. Every thing is working as expected but I am stuck in one point. I want to update the cart page, my page contains the icon buttons for updating and deleting the cart item in cart list. Button press is updating the cart in server as per expectation but I am stuck to update the UI for user. It is very important to update UI on successful server response to notify the user that your cart has been modified. I want to update this page without leaving this page for better user experience. I've attached my code here. I want to refresh the UI after server response. Please help me out. Here is my code. Thanks in advance.

class CartPage extends StatefulWidget{
  @override
  _CartPageState createState()=>_CartPageState();
}

class _CartPageState extends State<CartPage>{
  TextEditingController dateinput = TextEditingController();
  bool isLoading=true;
  String imageurl="http://192.168.10.8/DigicatDemo/Upload/Images/1/";
  late CartVM cartVM;


  void fetchData()async{
    Provider.of<CartDetailsVM>(context,listen: false).fetchCartDetailsList().then((value) => setState((){
      isLoading=false;
    }));
  }


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    cartVM = CartVM(context);
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    List<CartdetailsModel> cartDetailsList =
        Provider.of<CartDetailsVM>(context,listen: false).getCartDetailsList();

    Future<void> updateCart()async{
      Provider.of<CartDetailsVM>(context,listen: false).fetchCartDetailsList();
      setState(() {
        cartDetailsList =
            Provider.of<CartDetailsVM>(context,listen: false).getCartDetailsList();
        print('updateCart');
      });
    }

return isLoading?Center(child: CircularProgressIndicator())
        :  Scaffold(
      body: Column(
        children: [
SizedBox(height: 5.0,),
          Expanded(
              child:Padding(
                  padding:  EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 10.0),
                  child:SingleChildScrollView(
                    child: GridView.builder(
                        physics: ScrollPhysics(),
                        shrinkWrap: true,
                        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 5,
                          childAspectRatio: 0.75,
                          crossAxisSpacing: 10,
                          mainAxisSpacing: 10,
                        ),
                        itemCount: cartDetailsList.elementAt(0).cartgrid!.length,
                        itemBuilder: (BuildContext ctx, index) {
                          return GestureDetector(
                            onTap: ()=>{

                            },
                            child: Material(
                              elevation: 9,
                              shadowColor: Colors.red,
                              child: Container(
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15),
                                ),
                                child: Center(
                                  child: Column(
                                    children: [
                                      IconButton(icon: Icon(FontAwesome.trash),onPressed: (){
                                        showDialog(
                                            context: context,
                                            barrierDismissible: false,
                                            builder: (BuildContext context){
                                              return StatefulBuilder(builder: (context, setState){
                                                return AlertDialog(
                                                      title: Text("Are you sure you want to delete this product"),
                                                      actions: [
                                                        ElevatedButton(onPressed: (){
                                                          cartVM.deleteCartProduct(product_code:cartDetailsList.elementAt(0).cartgrid!.elementAt(index).ProductCode)
                                                              .then((value) => showDialog(context: context, builder: (BuildContext context){
                                                            return AlertDialog(
                                                              title: Text("Success"),
                                                              content: Text('Successfully deleted from the cart.'),
                                                              actions: [
                                                                ElevatedButton(onPressed: (){
                                                                  updateCart();
                                                                  Navigator.of(context).pop();
                                                                }, child: Text("Close")),
                                                              ],
                                                            );
                                                          }));
                                                           Navigator.of(context).pop();
                                                        }, child: Text("Yes")),
                                                        ElevatedButton(onPressed: (){
                                                          Navigator.of(context).pop();
                                                        }, child: Text("No")),
                                                      ],
                                                    );
                                              });                                              //
                                            });
                                      }),
                                

                          );
                        }),
                  )
              )
          ),

CodePudding user response:

First of all create your updateCart() method outside build method and now onPressed of button where you are deleting the item from cart after successful execution of event on server, call this method after it. Also create global variable of cartDetailsList instead of creating inside build method

CodePudding user response:

reading your question there is something you need to learn in flutter for a better understanding of how the the app function which is state management; we do have multiple states_management tools like getx or bloc but there is an inbuilt one which is setstate; please have a look on them and you will be able to resolve your question.

  • Related