Home > Blockchain >  Future function reloads infinitely? flutter
Future function reloads infinitely? flutter

Time:01-24

i am building a simple ecommerce app but i am stuck at a position when my future function reloads infinitely:

Future getCartData() async {
print("function one");
print("this is the token mytoken");
String url = 'https://myurl/apis/getCartItems';
http.Response response = await http.post(Uri.parse(url),
    headers: {
      'Authorization': "token mytoken",
      "Content-Type": "application/json",
    },
    body: json.encode({
      "username": "admin",
    }));
print(response.body);
var data = json.decode(response.body);
print("cart data recieved :");
print(data.length);
  //set state
 setState(() {
lengthData=data.length.toString();
totalPrice=0;
  });
   return data;
  }

i am using set state becouse i need to set this value once the data return but this set state reloading again and again when i remove it future function run only once but it not update the values of "lengthData" and "totalPrice".

my init function:

initState(){
getCartData();
super.initState();
 }

and here is my futurebuilder:

 child:FutureBuilder(
                future: getCartData(),
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
// still waiting for data to come
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasData &&
snapshot.data.isEmpty) {
return Center(child: Text("No Products"));
;
} else {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ListView.builder(

                   itemCount: snapshot.data!.length,
                    itemBuilder: (BuildContext context, index) {
List list = snapshot.data;
totalPrice = totalPrice   list[index]['price'];
print("this is the total:$totalPrice");
                      return Container(
                        margin: EdgeInsets.only(top: 20),
                        height: 130,
                        child: Stack(
                          children: <Widget>[
                            Align(
                              alignment: Alignment(0, 0.8),
                              child: Container(
                                  height: 100,
                                  margin: EdgeInsets.symmetric(
                                      horizontal: 16.0),
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      boxShadow: shadow,
                                      borderRadius: BorderRadius.only(
                                          bottomLeft: Radius.circular(10),
                                          bottomRight: Radius.circular(
                                              10))),
                                  child: Row(
                                      mainAxisAlignment: MainAxisAlignment
                                          .end,
                                      children: <Widget>[
                                        Container(
                                          padding: EdgeInsets.only(
                                              top: 12.0, right: 12.0),
                                          width: 200,
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment
                                                .start,
                                            children: <Widget>[
                                              Text(
                                                '${list[index]['title']}',
                                                textAlign: TextAlign.right,
                                                style: TextStyle(
                                                  fontWeight: FontWeight
                                                      .bold,
                                                  fontSize: 12,
                                                  color: darkGrey,
                                                ),
                                              ),
                                              Align(
                                                alignment: Alignment
                                                    .centerRight,
                                                child: Container(
                                                  width: 160,
                                                  padding: const EdgeInsets
                                                      .only(
                                                      left: 32.0,
                                                      top: 8.0,
                                                      bottom: 8.0),
                                                  child: Row(
                                                    mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                    children: <Widget>[
                                                      ColorOption(
                                                          Colors.red),
                                                      Text(
                                                        "\₹${list[index]['price']}",
                                                        textAlign: TextAlign
                                                            .center,
                                                        style: TextStyle(
                                                            color: darkGrey,
                                                            fontWeight: FontWeight
                                                                .bold,
                                                            fontSize: 18.0),
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                        Theme(
                                            data: ThemeData(
                                                accentColor: Colors.black,
                                                textTheme: TextTheme(
                                                  headline6: TextStyle(
                                                      fontFamily: 'Montserrat',
                                                      fontSize: 14,
                                                      color: Colors.black,
                                                      fontWeight: FontWeight
                                                          .bold),
                                                  bodyText1: TextStyle(
                                                    fontFamily: 'Montserrat',
                                                    fontSize: 12,
                                                    color: Colors.grey[400],
                                                  ),
                                                )),
                                            child: NumberPicker(
                                              value: 2,
                                              minValue: 1,
                                              maxValue: 10,
                                              onChanged: (value) {
                                                // setState(() {
                                                //   quantity = value;
                                                // });
                                              },
                                            ))
                                      ])),
                            ),
                            Positioned(
                                top: 5,
                                child: SizedBox(
                                  height: 150,
                                  width: 200,
                                  child: Stack(children: <Widget>[
                                    Positioned(
                                      left: 25,
                                      child: SizedBox(
                                        height: 150,
                                        width: 150,
                                        child: Transform.scale(
                                          scale: 1.2,
                                          child: Image.asset('assets/bottom_yellow.png'),
                                        ),
                                      ),
                                    ),
                                    Positioned(
                                      left: 50,
                                      top: 5,
                                      child: SizedBox(
                                          height: 80,
                                          width: 80,
                                          child: Image.network(
                                            '$Imagename',
                                            fit: BoxFit.contain,
                                          )),
                                    ),
                                    Positioned(
                                      right: 30,
                                      bottom: 25,
                                      child: Align(
                                        child: IconButton(
                                          icon: Image.asset('assets/red_clear.png'),
                                          onPressed: (){
                                              deleteCartData('${list[index]['id']}');
                                          },
                                        ),
                                      ),
                                    )
                                  ]),
                                )
                            ),
                          ],
                        ),
                      );

                    }

                ):Center(child: Text("no data"));
}
},
                )

can someone please help me and suggest me a better way to solve it <3. Thanks in Advance <3.

CodePudding user response:

You need to return a Future from your 'getCartData()' method, now you are returning just a Hashmap instead of a Future which the futureBuilder needs. You can do it like this:

return Future.value(data);

One more thing is that you must just pass the reference to the method and not call it, like this:

future: getCartData,

Also please specify the return types, use Future<Map<String, dynamic>> or whatever you are returning (this will help you in the future) :D

And one more, you don't need to call your method in 'initState()' since the FutureBuilder will do it for you :)

  •  Tags:  
  • Related