dart-code-checker/dart-code-metrics

[New rule] Avoid redundant .of(context) calls inside build method

enseitankad0 opened this issue · 3 comments

Calling Theme.of(context) is an expensive operation. If possible this value should be cached.

I've heard about this optimization in Geekle 2022 Junior Track
"The things you can do with .of(context)"

  • Warns about a potential error (problem)
  • Suggests an alternate way of doing something (suggestion)
  • Other (please specify:)

✅ GOOD

 @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    return Container(
      color: theme.disabledColor,
      child: Card(
        color: theme.primaryColor,
      ),
    );
  }

❌ BAD

 @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).disabledColor,
      child: Card(
        color: Theme.of(context).primaryColor,
      ),
    );
  }

[ADDITIONAL] I think this rule can be also used not only for .of call but should also suggest a developer to cache property instead of getting it every time when needed.

✅ GOOD

@override
  Widget build(BuildContext context) {
    final nameLength = user.userName.length;
    return Column(
      color: nameLength > 10 : Color.red : Color.blue,
      child: SizedBox(
        width : nameLength > 10 : 20.0 : 30.0
        child: Text('User')
      )
    );
  }

❌ BAD

 @override
  Widget build(BuildContext context) {
    return Column(
      color: user.userName.length > 10 : Color.red : Color.blue,
      child: SizedBox(
        width : user.userName.length > 10 : 20.0 : 30.0
        child: Text('User')
      )
    );
  }

@enseitankad0 have you tried https://dartcodemetrics.dev/docs/rules/common/prefer-moving-to-variable? Looks like it does exactly what you're asking for.

Yes. Sorry but I wasn't aware about this rule existence. Thank you so much!

You're welcome!