Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wait for value before calling method Flutter/Dart

I am having a pretty hard time with certain actions in flutter. I currently have a method in an outside class that updates a db that my widget relies on for displaying info. I am correctly updating the values in the db and updating the UI correctly. BUT I am having a hard time getting an input first, THEN having that method function. I have tried having it all in the same body and no dice, I have tried to have the addStock method show the input and does not work. The only thing that has been a ban-aid has been to use Navigator.push to the screen again or using a time delayed. Both have produced undesired consequences. I have also tried having the addStock method inside the displayAmountToADD on pressing okay and does not update UI.

//a button inside the UI
onPressed: () async {
       displayAmountToAdd(context, index);
           setState(() {});
         },
....

Future<void> displayAmountToAdd(
  BuildContext context,
  int index,
) async {
  final _textFieldController = TextEditingController();
  double materialKG = 0;

  showDialog(
    context: context,
    builder: (context) {
      return AlertDialog(
        title: Text('Enter amount to add'),
        content: Row(
          children: <Widget>[
            Expanded(
              child: TextField(
                onChanged: (materialQuanity) {
                  materialKG = double.parse(materialQuanity);
                },
                controller: _textFieldController,
                decoration: InputDecoration(hintText: "KG"),
              ),
            ),
          ],
        ),
        actions: <Widget>[
          TextButton(
            child: Text('OK'),
            onPressed: () {
              materialKG = double.parse(_textFieldController.text);
              addStock(context, mapM[index]['quanity'], mapM[index]['name'],
                  materialKG);

              Navigator.pop(context);
            },
          ),
          TextButton(
              child: Text("Cancel"),
              onPressed: () {
                Navigator.pop(context);
              })
        ],
      );
    },
  );
  //return Future.delayed(Duration(seconds: 4),()=>materialKG); //TRYING TO AVOID THIS
}



//outside the ui file
addStock(
  BuildContext context,
  double currentQuanity,
  String name,
  double amountToAdd
) async {
  //final db = await database;
  double newStock;

  late double materialKG;
newStock=currentQuanity+amountToAdd;
  await db.rawUpdate(
      'UPDATE materials SET quanity = $newStock WHERE name = "$name" ');
  mapM = await db.query('materials'); //update values
  //the following is only because setState is not working properly on other screen

  ScaffoldMessenger.of(context).showSnackBar(SnackBar(
    content: Text("Added $amountToAdd KG to $name"),
  ));
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

displayAmountToAdd and showDialog method are future. Use await before theses to hold method to finish.

A sample example:

const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
  await Future.delayed(oneSecond);
  print(message);
}

Learn more about async-await.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading