alienhana
alienhana

Reputation: 45

How do i pass a function as a parameter in dart?

Code down here keeps telling me that there's a problem in the syntax here onTap: onPress,

import 'package:flutter/material.dart';
class ReusableCard extends StatelessWidget {
  final Color color;
  final Widget? cardChild;
  final Function? onPress;
  ReusableCard({ this.cardChild, required this.color, this.onPress});
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        margin: const EdgeInsets.all(15.0),
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(15.0),
        ),
        child: cardChild,
      ),
    );
  }
}

Upvotes: 0

Views: 5752

Answers (3)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63799

Using final Function? onPress; is defined nullable function.

But onTap requires void function,

You can just do

  final Function()? onPress;

Or

onTap: () {
    if (onPress != null) onPress!();
  },

Using VoidCallback

/// Signature of callbacks that have no arguments and return no data.
typedef VoidCallback = void Function();

Hope you get the issue here. Also provide key on constructor.

class ReusableCard extends StatelessWidget {
  final Color color;
  final Widget? cardChild;
  final Function()? onPress;
  const ReusableCard({
    this.cardChild,
    required this.color,
    this.onPress,
    super.key,
  });

But I think it is pretty to use final GestureTapCallback? onPress;

Upvotes: 2

thenish
thenish

Reputation: 77

Function is null type, so it can be null.

You should write

onTap:(onPress!=null) ? onPress : null

Upvotes: 1

Kaushik Chandru
Kaushik Chandru

Reputation: 17812

Use voidcallback

class ReusableCard extends StatelessWidget {
  final Color color;
  final Widget? cardChild;
  final VoidCallback onPress;//here
  ReusableCard({ this.cardChild, required this.color, this.onPress});
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPress,
      child: Container(
        margin: const EdgeInsets.all(15.0),
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(15.0),
        ),
        child: cardChild,
      ),
    );
  }
}

or you can also do this

class ReusableCard extends StatelessWidget {
  final Color color;
  final Widget? cardChild;
  final Function? onPress;
  ReusableCard({ this.cardChild, required this.color, this.onPress});
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){onPress();},//create a method and call onPress here
      child: Container(
        margin: const EdgeInsets.all(15.0),
        decoration: BoxDecoration(
          color: color,
          borderRadius: BorderRadius.circular(15.0),
        ),
        child: cardChild,
      ),
    );
  }
}

Upvotes: 3

Related Questions