Flutter封装三目表达式

2023-02-02  本文已影响0人  大风车__

项目中为了简化代码经常写三目表达式,但有缺点,比如某个值包含多种状态,三目表达式就排不上用场了

例如

  Widget _buildTest(int type) {
    return Text(type == 0 ? "A" : "B"); 
  }

解决方案

  class ReturnBuilder {
    static T run<T>(T Function() callback) {
      return callback();
    }
  }

  Widget _buildTest(int type) {
    return Text(ReturnBuilder.run(() {
      if (type == 0) {
        return "A";
      } else if (type == 1) {
        return "B";
      } else if (type == 2) {
        return "C";
      }
      return "D";
    }));
  }
上一篇 下一篇

猜你喜欢

热点阅读