Skip to content

Commit 5374810

Browse files
authored
Fix scroll controller dispose (#47)
Only dispose controllers the widget created itself.
1 parent 966ee8f commit 5374810

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

lib/src/ui/session/chat_scroll_view.dart

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -62,30 +62,37 @@ class ChatScrollView extends StatefulWidget {
6262
}
6363

6464
class _ChatScrollViewState extends State<ChatScrollView> {
65-
ScrollController? _internalController;
65+
late ScrollController _scrollController;
66+
bool _isOwningScrollController = false;
6667
int _lastMessageCount = 0;
6768

68-
ScrollController get _controller => widget.scrollController ?? _internalController!;
69-
7069
@override
7170
void initState() {
7271
super.initState();
73-
_internalController = widget.scrollController ?? ScrollController();
72+
_setScrollController(widget.scrollController);
7473
}
7574

7675
@override
7776
void didUpdateWidget(ChatScrollView oldWidget) {
7877
super.didUpdateWidget(oldWidget);
7978
if (oldWidget.scrollController != widget.scrollController) {
80-
_internalController?.dispose();
81-
_internalController = widget.scrollController ?? ScrollController();
79+
_setScrollController(widget.scrollController);
80+
}
81+
}
82+
83+
void _setScrollController(ScrollController? ctrl) {
84+
if (_isOwningScrollController) {
85+
_scrollController.dispose();
8286
}
87+
_scrollController = ctrl ?? ScrollController();
88+
_isOwningScrollController = ctrl == null;
8389
}
8490

8591
@override
8692
void dispose() {
87-
if (widget.scrollController == null) {
88-
_internalController?.dispose();
93+
// Only dispose when this widget created the controller.
94+
if (_isOwningScrollController) {
95+
_scrollController.dispose();
8996
}
9097
super.dispose();
9198
}
@@ -107,10 +114,10 @@ class _ChatScrollViewState extends State<ChatScrollView> {
107114
if (!mounted) {
108115
return;
109116
}
110-
if (!_controller.hasClients) {
117+
if (!_scrollController.hasClients) {
111118
return;
112119
}
113-
unawaited(_controller.animateTo(
120+
unawaited(_scrollController.animateTo(
114121
0,
115122
duration: const Duration(milliseconds: 200),
116123
curve: Curves.easeOut,
@@ -130,7 +137,7 @@ class _ChatScrollViewState extends State<ChatScrollView> {
130137

131138
return ListView.builder(
132139
reverse: true,
133-
controller: _controller,
140+
controller: _scrollController,
134141
padding: widget.padding,
135142
physics: widget.physics,
136143
itemCount: messages.length,

0 commit comments

Comments
 (0)