Home > OS >  Can I Use "FutureBuilder()" under Void Method in Flutter
Can I Use "FutureBuilder()" under Void Method in Flutter

Time:11-28

This is My Code.

Future<void> SendOrderDetails() async{
  Row(
    children: [
      FutureBuilder(
      future: topcart.getData(),
        builder: (context, AsyncSnapshot<List<Cart>> snapshot) {
          for(int i = 0; i<itemcount; i  )
          {
            if(itemcount>listModel2.data!.length) {
              listModel2.data?.add(Model2(
                ORDER_INFO_ID: 1,
                PRODUCT_ED_ID: 2,
                QTY: quantitycalcule.toString(),
                UNIT_PRICE:'00',// snapshot.data![i].Book_initional_price!.toString(),
                CHGED_BY:1,
                CHGED_DATE: DateTime.now().toString(),
                STATUS: 'P',
              ),);
            }
          }
          return const Text('');
        }
       ),
    ],
   );
}

When I Call This, "FutureBuilder" did not run. I need "snapshot" in If condition. Please Help me.

CodePudding user response:

I'm not sure what your code is trying to accomplish but there are a few things I can see that could be potentially causing issues:

  1. You are calling FutureBuilder inside a Future and there is no await inside your future so it's really not going to work right.

The whole point of a FutureBuilder is to builds itself based on the latest snapshot of interaction with a Future. Maybe you can explain why this structure is the way it is.

  1. topcart.getData() - Should not be in the future builder. You need to get something like
// This needs to be outside the build method, maybe initState()
Future<TYPE> _gd = topcart.get() 

// Future Builder in the build method
FutureBuilder<String>(
        future: _gd, 
        builder: (BuildContext context, AsyncSnapshot<TYPE> snapshot) {});
  1. Ideally, within the FutureBuilder() you want to check connection and data like:
 if (snapshot.connectionState == ConnectionState.waiting) {
      return // Progress indicator widget
    } else if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasError) {
        return // Error Widget or Text 
      } else if (snapshot.hasData) {
        return // Process data here
      } else {
        return // Empty set returned
      }
    } else {
      return Text('State: ${snapshot.connectionState}');
    }

CodePudding user response:

this method returns nothing so you don't have way to check whether the future builder run or not, try to use print and check your debug console (or try to debug your code by using break points) if it works then do what ever you want to do additional question: what state management you are using?

  • Related