SafeList in Flutter and Dart小技巧

2022-12-10

这篇文章主要为大家介绍了SafeList in Flutter and Dart小技巧,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

目录
  • 正文
  • 封装一个SafeList
    • 测试一下

正文

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

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

虽然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的资料请关注北冥有鱼其它相关文章!

《SafeList in Flutter and Dart小技巧.doc》

下载本文的Word格式文档,以方便收藏与打印。