Last active
August 31, 2022 11:32
-
-
Save lslv1243/76b69bf7ce3bef8afe951228a19320c6 to your computer and use it in GitHub Desktop.
Flutter Infinite List Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/foundation.dart'; | |
class InfiniteListPage<T> { | |
final List<T> items; | |
final int totalCount; | |
InfiniteListPage(this.items, this.totalCount); | |
} | |
class InfiniteListController<T> extends ChangeNotifier { | |
final Future<InfiniteListPage<T>> Function(int offset) loadPage; | |
InfiniteListController({ | |
required this.loadPage, | |
}); | |
var _totalCount = -1; | |
var _loading = false; | |
var _items = <T>[]; | |
Exception? _exception; | |
Exception? get exception => _exception; | |
bool get loading => _loading; | |
List<T> get items => _items; | |
void reload() { | |
if (_loading) return; | |
_exception = null; | |
_totalCount = -1; | |
_items = []; | |
_loadPage(); | |
} | |
void loadMore() { | |
final hasMore = _items.length < _totalCount; | |
if (!hasMore || _loading) return; | |
_loadPage(); | |
} | |
void _loadPage() async { | |
_loading = true; | |
notifyListeners(); | |
try { | |
final page = await loadPage(_items.length); | |
_items = [..._items, ...page.items]; | |
_totalCount = page.totalCount; | |
} on Exception catch (exception) { | |
_exception = exception; | |
} finally { | |
_loading = false; | |
} | |
notifyListeners(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment