首页 > 解决方案 > Flutter:通知监听器,如何让onNotification动态化

问题描述

我是飞镖新手,因此会颤抖。我正在使用这样的 NotificationListener

   String x = a; // or could be x=b, x=c, etc, comes as function parameter 
    return NotificationListener(
          onNotification: onNotificationHandler,
          child: new ListView.builder(
              scrollDirection: Axis.horizontal,
              shrinkWrap: true,
              physics: const BouncingScrollPhysics(),
               // other codes comes here

问题,

我希望onNotification基于变量值的值是动态的x 有人可以帮助我吗?

标签: flutterdart

解决方案


在 Dart 中,Function是一等公民,这意味着一个函数可以从一个方法返回。

然后,您可以创建一个方法,该方法将其x作为参数并返回一个NotificationListenerCallback. 返回的函数就是所谓的 a Closure,这意味着x即使它在外部执行,它也可以访问其词法范围内的变量(在这种情况下是 is )。

在您的示例中,它可以是:

    String x = a; // or could be x=b, x=c, etc, comes as function parameter 
    return NotificationListener(
      onNotification: _notificationHandler(x), // The return the appropriate function with x scoped to the function to be used later
      child: new ListView.builder(
      // other codes comes here

def _notificationHandler(String value) => (T notification) {
  // Note that the returned function has access to `value`
  // even if it will be executed elsewhere
  return (value == 'Hey); 
}

推荐阅读