Thanks to visit codestin.com
Credit goes to github.com

Skip to content

MaterialStateColor.resolveWith cannot return null value. #116590

Closed
@TahaTesser

Description

@TahaTesser

I've come across this in previous PRs and in a recent PR.

Take this as an example where Color? get selectedColor is nullable but MaterialStateColor.resolveWith doesn't allow returning a null value.

In a case where we need to return a null so an "effectiveColor" variable can fall back to a different color for the default property.

  @override
  Color? get selectedColor => MaterialStateColor.resolveWith((Set<MaterialState> states) {
    if (states.contains(MaterialState.selected)) {
      return _themeData.colorScheme.primary;
    }
    
    // cannot return a null.
    return null;
  });

I would have to provide a condition to avoid getting Colors.transparent, like this.

  @override
  Color? get selectedColor =>  _themeData.colorScheme.primary;
   /// ....
    final Color? effectiveSelectedColor = MaterialStateProperty.resolveAs<Color?>(selectedColor, states)
      ?? MaterialStateProperty.resolveAs<Color?>(tileTheme.selectedColor, states)
      ?? MaterialStateProperty.resolveAs<Color?>(theme.listTileTheme.selectedColor, states)
      ?? (states.contains(MaterialState.selected) ? defaults.selectedColor : null);

I've noticed this pattern throughout the framework where MaterialStateColor.resolveWith often resorts to Colors.transparent. I would like to make sure this doesn't go unnoticed if it is by design and if there is a way to return null.

Here are some instances:

if (states.contains(MaterialState.hovered)) {
return _colors.onSurface.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return _colors.onSurface.withOpacity(0.12);
}
return Colors.transparent;
},

}
return Colors.transparent;
}
if (states.contains(MaterialState.pressed)) {
return _colors.primary.withOpacity(0.12);
}
if (states.contains(MaterialState.hovered)) {
return _colors.onSurface.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return _colors.onSurface.withOpacity(0.12);
}
return Colors.transparent;

Color? get overlayColor => MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return _colors.primary.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return _colors.primary.withOpacity(0.12);
}
if (states.contains(MaterialState.dragged)) {
return _colors.primary.withOpacity(0.12);
}
return Colors.transparent;
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    f: material designflutter/packages/flutter/material repository.frameworkflutter/packages/flutter repository. See also f: labels.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions