广告
返回顶部
首页 > 资讯 > 移动开发 >SafeList in Flutter and Dart小技巧
  • 156
分享到

SafeList in Flutter and Dart小技巧

SafeList Flutter DartFlutter Dart技巧 2022-12-08 20:12:25 156人浏览 八月长安
摘要

目录正文封装一个SafeList测试一下正文 最近遇到一些列表的错误,例如,列表为空时直接调用方法会报错。 一般都会在使用前判断列表是否为空,再使用。 虽然Flutter提供了N

正文

最近遇到一些列表的错误,例如,列表为空时直接调用方法会报错。

一般都会在使用前判断列表是否为空,再使用。

虽然Flutter提供了Null safety,但是用的时候还是会忘记或者忽略,直接使用'!'来跳过非空判断。

封装一个SafeList

代码如下:

class SafeList<T> extends ListBase<T> {
    final List<T> _list;
    final T defaultValue;
    final T absentValue;
    SafeList({
        required this.defaultValue,
        required this.abssentValue,
        List<T>? values,
    }) : _list = values ?? [];
    @override
    T operator [](int index) => index < _list.length ? _list[index] : absentValue;
    @override
    void operator []=(int index, T value) => _list[index] = value;
    @override
    int get length => _list.length;
    @override
    T get first => _list.isNotEmpty ? _list.first : absentValue;
    @override
    T get last => _list.isNotEmptu ? _list.last : absentValue;
    @override
    set length(int newValue) {
        if (newValue < _list.length) {
            _list.length = newValue;
        } else {
            _list.addAll(List.filled(newValue - _list.length, defaultValue));
        }
    }
}

测试一下

void main() {
    const notFound = 'NOT_FOUND';
    const defaultString = '';
    final MyList = SafeList(
        defaultValue: defaultString,
        absentValue: notFount,
        values: ['Bar', 'Baz'],
    );
    print(myList[0]);// Bar
    print(myList[1]);// Baz
    print(myList[2]);// NOT_FOUND
    myList.length = 4;
    print(myList[3]);// ''
    myList.length = 0;
    print(myList.first);// NOT_FOUND
    print(myList.last);// NOT_FOUND
}

有时胡乱思考的一个小tips,如有更好的建议欢迎留言共同进步。

以上就是SafeList in Flutter and dart小技巧的详细内容,更多关于SafeList Flutter Dart的资料请关注编程网其它相关文章!

--结束END--

本文标题: SafeList in Flutter and Dart小技巧

本文链接: https://www.lsjlt.com/news/174594.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作