mirror of
https://github.com/flutter/samples.git
synced 2026-03-24 21:31:47 +00:00
It only checks if [startingIndex] is greater than [catalogLength] in the existing implementation. It doesn't check the index of an item in a page. So it may generate more items than the number specified by [catalogLength]. i.e if [catalogLength] is 113, the existing implementation will still generate 120 items. This PR solves the issue by adding the check for the indices of items in a page.
45 lines
1.4 KiB
Dart
45 lines
1.4 KiB
Dart
// Copyright 2020 The Chromium Authors. All rights reserved.
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
// found in the LICENSE file.
|
|
|
|
import 'dart:math';
|
|
import 'package:flutter/material.dart';
|
|
|
|
import 'item.dart';
|
|
import 'page.dart';
|
|
|
|
const catalogLength = 200;
|
|
|
|
/// This function emulates a REST API call. You can imagine replacing its
|
|
/// contents with an actual network call, keeping the signature the same.
|
|
///
|
|
/// It will fetch a page of items from [startingIndex].
|
|
Future<ItemPage> fetchPage(int startingIndex) async {
|
|
// We're emulating the delay inherent to making a network call.
|
|
await Future<void>.delayed(const Duration(milliseconds: 500));
|
|
|
|
// If the [startingIndex] is beyond the bounds of the catalog, an
|
|
// empty page will be returned.
|
|
if (startingIndex > catalogLength) {
|
|
return ItemPage(
|
|
items: [],
|
|
startingIndex: startingIndex,
|
|
hasNext: false,
|
|
);
|
|
}
|
|
|
|
// The page of items is generated here.
|
|
return ItemPage(
|
|
items: List.generate(
|
|
min(itemsPerPage, catalogLength - startingIndex),
|
|
(index) => Item(
|
|
color: Colors.primaries[index % Colors.primaries.length],
|
|
name: 'Color #${startingIndex + index}',
|
|
price: 50 + (index * 42) % 200,
|
|
)),
|
|
startingIndex: startingIndex,
|
|
// Returns `false` if we've reached the [catalogLength].
|
|
hasNext: startingIndex + itemsPerPage < catalogLength,
|
|
);
|
|
}
|