Conditionally pass optional parameter to widget

Viewed 1323

I have a custom widget which can optionally be passed a size property. If present, this value should be passed to the size property of an Icon() widget within my own widget.

Is there a way to only pass this value if it's present?

class MyWidget extends StatelessWidget {
  final double size;
  MyWidget({this.size});

  Widget build(BuildContext context) {
    return Icon(
      iconData: IconData(),
      size: // Don't pass size here if not present
    );
  }
}
1 Answers

I ran into similar problem where I have to optionally display an icon in a button.

With null safety, what you're trying to do can be achieved this way

import 'package:flutter/material.dart';

class MyWidget extends StatelessWidget {
  final double? size;
  MyWidget ({this.size});

  Widget build(BuildContext context) {
    return Icon(
      iconData:IconData(),
      size: size, // Don't pass size here if not present
    );
  }
}

And used like this

 StackIcon()

or like this

 StackIcon(size: 100.0)

If you supply the size parameter the icon will make use of it, otherwise it uses the default size of the icon.
Related