6

I have a custom widget which has a button. I want to create VoidCallback faction to return data from it.

onDayPressed: (DateTime date, List<Event> events){
   // I want to return date time to original class when the user changes the date 
}

i try to do this but doesn't work

onDayPressed: (DateTime date, List<Event> events) => widget.onDayChanged,

// on original class

CustomCalender(onDayChanged: (){print("HI");}),

I'm using this flutter package

flutter_calendar_carousel

Dharmesh Mansata
  • 4,422
  • 1
  • 27
  • 33
prg.dev
  • 141
  • 1
  • 3
  • 16

1 Answers1

17

If you need to pass data from child to parent you must use Function(T), since a VoidCallback do not support passing data. See the code example below:

// Try adapting this code to work with your code, the principle should be the same.
class MinimalExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // Notice the variable being passed in the function.
      body: ReturnValueToParent( myNumber: (int) => print(int),),
    );
  }
}

// Specify a Function(DateTime) in your case and adapt it to your problem.
class ReturnValueToParent extends StatelessWidget {
  final Function(int) myNumber;
  const ReturnValueToParent({Key key, this.myNumber}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: RaisedButton(
        // Remember the parameter
        onPressed: () => myNumber(5),
      ),
    );
  }
}
Tor-Martin Holen
  • 1,359
  • 1
  • 13
  • 19
  • Thank you that work. i have small question. what do you mean by => `: super(key: key); ` and why you put ` const ` key word in the beginning of class name ? I'm new to flutter and i try to learn it. Thanks – prg.dev Jul 29 '19 at 07:30
  • 1
    ": super(key: key);" is a call to the StatelessWidget's constructor. In Flutter keys are important to differentiate widgets in animations, lists, and various situations. In Android Studio if you hit alt + enter (option + enter) after writing the final variable(s) there is a suggestion which will auto-complete the constructor for you. The const keyword has a good explanation here: https://stackoverflow.com/questions/21744677/how-does-the-const-constructor-actually-work Hope it helps :-) – Tor-Martin Holen Jul 29 '19 at 07:46
  • understood, Thanks a lot :) – prg.dev Jul 29 '19 at 08:13