識react native再學react就易上手好多
睇你覺得學一樣獨立野定點
ListView.builder
// providers
final filteredMovesProvider = StateProvider.autoDispose<List<Move>>((ref) {
final searchText = ref.watch(searchTextProvider);
final moves = ref.watch(movesProvider);
if (searchText.isEmpty || searchText.trim().isEmpty) {
return moves;
} else {
return moves
.where((item) =>
item.name.removeWhitespace().toLowerCase().contains(searchText.removeWhitespace().toLowerCase()) ||
item.id.toString().contains(searchText))
.toList();
}
});
// MovePage
final filteredList = ref.watch(filteredMovesProvider);
return ListView.builder(
itemCount: filteredList.length,
itemBuilder: (context, index) {
Visibility
widget 去控制show邊個listRiverpod
嘅 FutureProvider
StateNotifierProvider
StateNotifier
StateNotifier
嘅state可以係int, bool或者其他immutable typeList<Move>
watch
呢個state嘅widget都會自動rebuildStateNotifier
可以define method去change statefetchData()
就係用嚟download dataclass MovesController extends StateNotifier<List<Move>> {
MovesController({required IMoveRepository repository})
: _repository = repository,
super([]); // initial state: empty list
final IMoveRepository _repository;
Future<void> fetchData({int limit = 20, int offset = 0}) async {
final moves = await _repository.fetchData(limit: limit, offset: offset);
state = [...state, ...moves]; // change state
}
int get count => state.length;
}
// provider
final movesControllerProvider = StateNotifierProvider<MovesController, List<Move>>((ref) {
final repository = ref.watch(moveRepositoryProvider);
return MovesController(repository: repository);
});
fetchData()
onPressed()
callback 入面唔可以用 ref.watch()
ref.read()
同埋係read <yourStateNotifierProvider>.notifier
// move_page.dart
// inside build method
final moves = ref.watch(movesControllerProvider);
return Scaffold(
body: moves.isEmpty
? Center(
child: ElevatedButton(
onPressed: () {
ref.read(movesControllerProvider.notifier).fetchData();
},
child: const Text('Press to download data'),
),
)
: Column(
children: [
Expanded(
child: ListView.builder(
...
),
),
ElevatedButton(
onPressed: () {
final currentCount = ref.read(movesControllerProvider.notifier).count;
ref.read(movesControllerProvider.notifier).fetchData(offset: currentCount);
},
child: const Text('Press to download more data'),
),
],
),
);