Home > Blockchain >  Constant constructor and Function in Dart
Constant constructor and Function in Dart

Time:11-14

I want onPressed it print a text, but it throw an error.

Invalid constant value

Why i can't use onPressed when using const? Can someone explain? Sorry i'm newbie.

 const IconButton(
        icon: Icon(
          Icons.search,
          color: Colors.white,
        ),
        tooltip: 'Search',
        onPressed: () => print('Hello'),
      )

CodePudding user response:

You are declaring IconButton widget as a const, which requires all of its children to be const as well, but the onPressed arrow function is dynamic and allocated at runtime therefore it is not constant.

The reason for this is that Flutter uses the const keyword as an idicator for a widget to never rebuild as it will get evaluated at compile time and only once. Hence, every part of it has to be constant as well.

To fix this, you should not use a const with Icon widget not with whole button widget.

IconButton(
 icon: const Icon(
   Icons.search,
   color: Colors.black,
   ),
 tooltip: 'Search',
 onPressed: () => print("hello"),
 )

CodePudding user response:

You can, however anonymous functions cannot be const in dart. Everything passed into your IconButton needs to be const in order for IconButton to be const. That said, standalone functions and static functions can be used as const:

// should be a standalone function (or a static function)
void hello() {
  print('Hello');
}

And then you can use IconButton as const:

 const IconButton(
        icon: Icon(
          Icons.search,
          color: Colors.white,
        ),
        tooltip: 'Search',
        onPressed: hello,
      )
  • Related