Search code examples
flutterdartcode-analysis

Don't create a lambda when a tear-off will do


@override
  Widget build(BuildContext context) {
    return GestureDetector(
      key: Key('${authText}button'),
      onTap: () => onTapFunction(),
      child: Container(
        height: 30.h,
        width: 150.w,
        decoration: BoxDecoration(
          color: bgColor,
          borderRadius: const BorderRadius.all(
            Radius.circular(10),
          ),
        ),
        child: Center(
          child: Text(
            authText,
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.sp,
              fontFamily: 'Corporate-Rounded',
            ),
          ),
        ),
      ),
    );
  }

In onTap: () => onTapFunction() code, verygood analysis pub.dev/packages/very_good_analysis (flutter code analysis) complaint that "Don't create a lambda when a tear-off will do". Anyone explain what is lambda in dart ?


Solution

  • My guess is that onTapFunction looks like this: void onTapFunction(), or maybe like this Future<void> onTapFunction() async. The point is that is's a function that takes no arguments and returns no value, similarly, the lambda you are making () => <SOMETHING> also takes no arguments and also returns no value. That means you could skip the lambda completely by simply passing the function by reference similar to how you might pass any other variable:

    From:

    onTap: () => onTapFunction(),
    

    To:

    onTap: onTapFunction,