Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does onTap VoidCallback handler work when it's an async (returning a Future<Null>)?

Tags:

flutter

dart

I'm trying to push a route to display a ListView item when that item is tapped (onTap). The onTap property for InkWell is defined as a VoidCallback. However, I would like to be able to receive a return value from the callback, indicating whether the user has modified said item in the dialog that was opened.

Assigning a Future<Null> async function to onTap seems to be OK, as per the Shrine Demo (shrine_home.dart in the flutter_gallery example):

  Future<Null> _showOrderPage(Product product) async {
    final Order order = _shoppingCart[product] ?? new Order(product: product);
    final Order completedOrder = await Navigator.push(context, new ShrineOrderRoute(
      order: order,
      builder: (BuildContext context) {
        return new OrderPage(
          order: order,
          products: _products,
          shoppingCart: _shoppingCart,
        );
      }
    ));
    assert(completedOrder.product != null);
    if (completedOrder.quantity == 0)
      _shoppingCart.remove(completedOrder.product);
  }

Why and how is this working? Thanks.

like image 472
Yaya Avatar asked Jun 27 '26 20:06

Yaya


1 Answers

Dart allows you to use a function with a non-void return value as a function with a void return value. The function will still return values as normal, but the analyzer will infer that they're of the void type and will complain if you try to use them, unless you cast them back to something else.

typedef void VoidCallback();
typedef int IntCallback();

final IntCallback i = () => 42;

void main() {
  final VoidCallback v = i;
  print("${v()}");        // prints 42
  print(v() as int);      // also prints 42
  print(v().toString());  // also prints 42, but analyzer complains:
                          // method 'toString' isn't defined for class 'void'
}

That is why you can use a function that returns a Future<Null> as a VoidCallback.

like image 59
Collin Jackson Avatar answered Jun 29 '26 09:06

Collin Jackson