Islomkhuja Akhrarov
Islomkhuja Akhrarov

Reputation: 1400

Cannot assign value to the outer function variable in then function in dart

I'm getting data from REST API.

And check if my data which gotten from api is not null.

fun(order,phone){
bool isNotNull;
// repository.myOrder(order, "998$phone") is function which get data from Rest api
     repository.myOrder(order, "998$phone").then((value) {
       if (value != null) {
         isNotNull=true;
         _showOrder.sink.add(value);
       } else {
         print("ELSE B:${isNotNull}");
         isNotNull = false;
         print("ELSE A:${isNotNull}");
         Fluttertoast.showToast(msg: "Not found");
       }
     });
   }

My isNotNull variable is always null. It is not waiting to be assigned.

Upvotes: 1

Views: 871

Answers (2)

Andrey Gritsay
Andrey Gritsay

Reputation: 976

You should avoid callback hell, try this:

Future<void> fun(order, phone) async {
    final value = await repository.myOrder(order, "998$phone");
    value != null ? _showOrder.sink.add(value) : Fluttertoast.showToast(msg: "Not found");
  }

Upvotes: 2

srikanth7785
srikanth7785

Reputation: 1512

You have to use setState for it to work..

fun(order,phone){
bool isNotNull;
// repository.myOrder(order, "998$phone") is function which get data from Rest api
     repository.myOrder(order, "998$phone").then((value) {
       if (value != null) {
        setState((){
          isNotNull=true;
         });
         _showOrder.sink.add(value);
       } else {
         print("ELSE B:${isNotNull}");
         setState((){
          isNotNull=false;
         });
         print("ELSE A:${isNotNull}");
         Fluttertoast.showToast(msg: "Not found");
       }
     });
   }

Hope it works for you..

Upvotes: 1

Related Questions