Skip to content

Instantly share code, notes, and snippets.

@ttlg
Last active December 25, 2020 06:35
Show Gist options
  • Save ttlg/f5af0c9aa265b610cdfa8aa53178779b to your computer and use it in GitHub Desktop.
Save ttlg/f5af0c9aa265b610cdfa8aa53178779b to your computer and use it in GitHub Desktop.
InifinityScrollSample
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
void main() async {
runApp(ProviderScope(child: InifinityScrollSample()));
}
final itemsProvider = StateProvider<List<String>>((ref) => null);
final itemController =
Provider<ItemController>((ref) => ItemController(ref.read));
class ItemController {
final Reader _read;
ItemController(this._read);
bool _isLoading = false;
bool _hitTheBottom = false;
List<String> get _items => _read(itemsProvider).state;
int get listLength => (_items?.length ?? 0) + (_hitTheBottom ? 0 : 1);
Future<void> loadItemsIfNeeded() async {
if (_isLoading || _hitTheBottom) {
return;
}
_isLoading = true;
await Future.delayed(const Duration(seconds: 1));
_read(itemsProvider).state = [
...(_items ?? []),
'Item ${_items?.length ?? 0}',
'Item ${(_items?.length ?? 0) + 1}'
];
_isLoading = false;
if (10 <= _items.length) {
_hitTheBottom = true;
}
}
}
class InifinityScrollSample extends HookWidget {
@override
Widget build(BuildContext context) {
final List<String> items = useProvider(itemsProvider).state;
return MaterialApp(
home: Scaffold(
body: ListView.builder(
itemCount: context.read(itemController).listLength,
itemBuilder: (context, int index) {
if (index < (items?.length ?? 0)) {
return Text(items[index]);
}
context.read(itemController).loadItemsIfNeeded();
return const LinearProgressIndicator();
},
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment