Flutter封装三目表达式

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

例如

  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";
    }));
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容