简体   繁体   中英

Conditionally pass optional parameter to widget

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
    );
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM