Home > Net >  How to pass function to dart constructor?
How to pass function to dart constructor?

Time:10-23

I want to define a constructor that takes fanction as parameter and return a value Like this:

class app {
 app({itemBuilder: itemBuilder});

  int itemBuilder(int? index) {
    return 1;
  }
}

CodePudding user response:

The question is unclear, but here is a snippet of passing the function as a parameter

class app {
 final Function app;

 app({this.itemBuilder: itemBuilder});

}

final obj = app(itemBuilder: (){

})

CodePudding user response:

I think what you need is the static function to create and return a value.

class AppData890 {
  
 
static int itemBuilder(int index) {
    return 1;
  }
}

use it like this

AppData890.itemBuilder(1);

If you need it as you state the question Tornike is ri8. for more info about static head to https://dart.dev/guides/language/language-tour#class-variables-and-methods

CodePudding user response:

Flutter doesn't allow what you did because The default value of an optional parameter must be constant. Just try with this

class app {
 app({itemBuilder});

  int itemBuilder(int? index) {
    return 1;
  }
}

or you can also try and no need to use constructor.

class app {
  static int itemBuilder(int? index) {
    return index??1;
  }
}
// call from outside

app.itemBuilder(5);
  • Related