SafeList in Flutter and Dart小技巧

Oria ·
更新时间:2024-09-20
· 1710 次阅读

目录

正文

封装一个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的资料请关注软件开发网其它相关文章!



dart IN AND 技巧 flutter

需要 登录 后方可回复, 如果你还没有账号请 注册新账号