fix: document getting first or last node exception (#885)

This commit is contained in:
LinJi 2024-09-11 17:51:35 +08:00 • committed by GitHub
commit c3c700524c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 15 additions and 5 deletions

View file

@ -75,15 +75,15 @@ class Document {
final Node root; final Node root;
/// First node of the document. /// First node of the document.
Node? get first => root.children.first; Node? get first => root.children.firstOrNull;
/// Last node of the document. /// Last node of the document.
Node? get last { Node? get last {
var last = root.children.last; Node? current = root.children.lastOrNull;
while (last.children.isNotEmpty) { while (current != null && current.children.isNotEmpty) {
last = last.children.last; current = current.children.last;
} }
return last; return current;
} }
/// Must call this method when the [Document] is no longer needed. /// Must call this method when the [Document] is no longer needed.

View file

@ -220,4 +220,14 @@ void main() async {
final last = document.last!; final last = document.last!;
expect(last.delta!.toPlainText(), secondChild); expect(last.delta!.toPlainText(), secondChild);
}); });
test('Document.blank().first is null', () {
final document = Document.blank();
expect(document.first, isNull);
});
test('Document.blank().last is null', () {
final document = Document.blank();
expect(document.last, isNull);
});
} }