Home > Back-end >  The right way to write this Stateless Widget
The right way to write this Stateless Widget

Time:02-01

I have the following stateless widget that shows an SVG image:

class MessageReactionWidget extends StatelessWidget {
  Widget icon;
  final double size;
  final Color backgroundColor;
  final double _ratio = 0.75;

  MessageReactionWidget(String reaction, {Key key, this.size = 40.0, this.backgroundColor = Colors.white})
      : super(key: key) {
    switch (reaction) {
      case 'like':
      case 'funny':
        icon = SvgPicture.asset('assets/images/icons/smile.svg', height: size * _ratio, color: Styles.colorSteadyState);
        break;
      case 'love':
        icon = SvgPicture.asset('assets/images/icons/heart.svg', height: size * _ratio, color: Styles.colorSteadyState);
        break;
      case 'wow':
        icon = SvgPicture.asset('assets/images/icons/clap.svg', height: size * _ratio, color: Styles.colorSteadyState);
        break;
      case 'thumbsdown':
        icon = SvgPicture.asset('assets/images/icons/thumbsdown.svg',
            height: size * _ratio, color: Styles.colorSteadyState);
        break;
      case 'sad':
        icon = SvgPicture.asset('assets/images/icons/sad.svg', height: size * _ratio, color: Styles.colorSteadyState);
        break;
      default:
        icon =
            SvgPicture.asset('assets/images/icons/thumbsup.svg', height: size * _ratio, color: Styles.colorSteadyState);
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: icon,
        alignment: Alignment.center,
        height: size,
        width: size,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: backgroundColor,
        ));
  }
}

This works fine, but Flutter gives a warning because icon is not final:

This class (or a class that this class inherits from) is marked as '@immutable', but one or more of its instance fields aren't final: MessageReactionWidget.icon

The icon will not change because it is set in the constructor, but it can't be marked final because it is not set immediately. What is the right way to handle this?

CodePudding user response:

You should change it from a StatlessWidget to a StatefullWidget. Update the icon value from inside a setState bloc, so the UI is updated correctly.

ex

setState(() {
  icon = someWidget;
});

CodePudding user response:

if you have a field that you initialized later in the code add late before that field like this.

late Widget icon
  •  Tags:  
  • Related