Flutter infinite scroll

Flutter infinite scroll DEFAULT

Flutter Infinite Scroll using Flutter only

In this tutorial we will go through the process of creating a list that will give you additional functionality to build and infinite scrolling list. It will have the Provider architecture setup with a view and a model to manage the state and business logic of that view. I've created a basic project that we'll use to build the functionality in. I have a basic starting project with one view, one viewmodel, a list of items and a ListView widget setup. You can download it here

The Problem

The problem I'm trying to solve is the ability to request more results when the user gets close to the bottom of the list. In addition to that I don't want it to depend on an arbitrary scroll position of the controller. That's different for every device, instead I'd like to request more data when a specific index is reached, or in our case, when a specific list item has been created.

The Solution

We'll create a list item widget that will fire off a callback when it's been initialised. We'll use an index threshold to determine if we've reached the correct location in the list then based on that make a request using the model to get more data.

Implementation

We'll start off with the UI so we can get that out of the way

UI Implementation

Create a new folder called widgets, and it it a file called creation_aware_list_item.dart. To start off, we'll create a widget that fires off a callback function when it has been initialised. We'll pass in a function called itemCreated which we'll fire off when the item initialisation is complete. It will also take the child widget so we can supply the UI from the outside.

Then we can head over to the home_view and surround our with a .

Reload the app and scroll to the bottom. Now you'll see

Now a question might come up, "Why didn't we just use the builder function for the itemBuilder to perform whatever logic we need?" . It's a good question, and a valid one. I think mixing responsibilities is dangerous for long term maintenance. The itemBuilder function is provided so that we can return a widget for the UI to show, not for use to calculate if we should be requesting new data. For that reason we created a widget that specifically allows you to notify it's parent that it has been initialised, through that functionality we can now make decisions "outside" of the functionality of the builder function.

Now that we have this functionality all we want to do is pass the index into the viewmodel. So we can replace

with

Logic Implementation

Open up the HomeViewModel and we'll add a new function that returns a called . What we want to do in this function is firstly determine if we have to request new data, then we want to determine which page of results we're requesting, and lastly we want to ensure we don't request the same data twice. With the code below we ensure the items are requested when the last item in the list is constructed. With the additional check that sees if the pageToRequest is bigger than the current page we ensure that we won't do a request for something that's already been requested so no additional guards needed.

Lets handle the loading indicator before we continue.

Loading indicator

What I like to do is show an additional list item at the bottom of the list while we're fetching more data. When the new data comes back I remove the item and show the additional data. The way we'll do that is by inserting an item into the list that specifically identifies it as a busy indicator. You can use anythting to uniquely identify your list item, since the list is made up of only strings I'll use something that would unlikely be one of the list items.

Create a new folder called constants and inside create a file called ui_constants.dart

We'll use this value to show a busy indicator instead of the title. Head over to the list_item and for the child of the container check if it equals the and show a else we'll continue showing the title.

That takes care of the UI. Lets create the functions to add and remove this list item when we have to show it. In the create two new functions and .

This functions will insert/remove the and notify the view that the items are updated so it can re-render the list of items. Now we can go ahead and show the indicator, delay the function a bit, "fetch new data" by generating it, adding it in and then removing the loading indicator. Update the loading indicator and replace the todo with the following code.

If you run the code now and scroll to the bottom you'll probably get this exception

This is because we are calling a rebuild while the item is still in the render process. We can use the to make sure the items are refreshed after the current frame that is being drawn. Change the call to handleItemCreated to in the HomeView

If you run the code now you'll see the items requested, a loading indicator for 5 seconds and then new results with the page number on it that's added. In a real environment all you'll do is replace the generate call with an actual request to your api, passing in the page number and then add the results into the list. Additionally if you have a limit to the number of results you can indicate that from your api by letting the caller know if there's more results to be requested.

That's it for this tutorial. This is a solution with the least amount of guards, pageNumbers built in, it won't request multiple times or every frame as the controller solution does, I hope that helped you. Let me know if you have any questions over on the Slack.

Sours: https://www.filledstacks.com/post/flutter-infinite-scroll-using-flutter-only/

How to do infinite scroll with pagination in flutter

Edit change sendPagesDataRequest to the following should work
if json string you gave me is correct

Edit
full code with new sendPagesDataRequest

Edit
you need to change , I use static string
Assume your json string like this

Edit working demo

enter image description here

Edit full code

You can use package https://pub.dev/packages/flutter_paginator
It will auto call your with parameter
In the following demo, I add print message , so you can see it auto call rest with page when scroll down
You can copy paste run full code below

code snippet

working demo

enter image description here

full demo code

Output

Sours: https://stackoverflow.com/questions/59234169/how-to-do-infinite-scroll-with-pagination-in-flutter
  1. Panasonic wireless camera
  2. Ranger drill
  3. Equinox 600 settings
  4. Firebase http functions

putraxor/infinite_scroll.dart

import'dart:async';import'package:flutter/material.dart';classInfiniteScrollextendsStatefulWidget {@override_InfiniteScrollStatecreateState() =>new_InfiniteScrollState();}class_InfiniteScrollStateextendsState<InfiniteScroll> {List<String> _data = [];Future<List<String>> _future;int _currentPage =0, _limit =10;ScrollController _controller =ScrollController(initialScrollOffset:0.0, keepScrollOffset:true);///constructor_InfiniteScrollState() { _controller.addListener(() {var isEnd = _controller.offset == _controller.position.maxScrollExtent;if (isEnd)setState(() { _future =loadData(); }); }); _future =loadData(); }///Mimic load dataFuture<List<String>>loadData() async {for (var i = _currentPage; i < _currentPage + _limit; i++) { _data.add('Data item - $i'); } _currentPage += _limit;return _data; }@overrideWidgetbuild(BuildContext context) {returnnewScaffold( appBar:AppBar( title:Text('Infinite Scrolling'), ), body:FutureBuilder( future: _future, builder: (BuildContext context, AsyncSnapshot snapshot) {if (snapshot.hasData) {List<String> loaded = snapshot.data;returnListView.builder( itemCount: loaded.length, controller: _controller, itemBuilder: (BuildContext context, int index) {returnListTile( title:Text(loaded[index]), onTap: () {}, ); }, ); }returnLinearProgressIndicator(); }, ), ); }}
Sours: https://gist.github.com/putraxor/6437465b7cdc3b5134c39b8a978801f7
Pagination Infinite Scrolling with Flutter

Infinite scrolling list with Flutter - Flutter Pagination Example

There are lots of apps that contains feature lists. Sometimes app needs to build lists of settings, lists of todo items, lists of Images, lists of posts etc. While fetchin these data somw time the data could scroll endlessly. Examples like a Twitter timeline, a Facebook feed or a list of posts on Reddit etc...

How to build this infinite scrolling list in flutter. In this post we will create Flutter Pagination with infinite scroll.

To implement this pagination we will use pagination plugin. If we are getting data from network or local as JSON, this json will treat as Map and we need to convert data in flutter Map to List , then we can load this list to listView.

Load Infinite List data with PaginationList widget

Conclusion
I think now you know how to build this infinite scrolling list in flutter. In this post we will create infinite scroll pagination data with flutter.

My Other Posts
Flutter Form Validation

Sours: https://dev.to/rrtutors/infinite-scrolling-list-with-flutter-flutter-pagination-example-4275

Infinite scroll flutter

How to implement infinite scrolling with ListView in Flutter?

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

 is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with  and ,  with support for date range and time picker with the new style.

flutter_DatePicker

New  format

Other than these widget updates there is some update within the project also like in  file format. If you are a flutter plugin publisher then your old   is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the method.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Sours: https://morioh.com/p/3e7f976003f4
Flutter - Infinite Scrolling Pagination for ListView - Flutter UI

Infinite Scrolling Pagination in Flutter

Forget about the gold at the end of the rainbow. Have you ever wondered what’s at the end of your Instagram feed? Has anyone ever scrolled that far? You could find the password to a secret Swiss bank account, the key to immortality or the answer to the meaning of life. Oh, the possibilities.

Today you’ll not only solve that mystery, but will also master this very same infinite scrolling technique. The technique has many names, including infinite scrolling pagination, endless scrolling pagination, auto-pagination, lazy loading pagination, continuous scroll pagination and progressive loading pagination.

By the end of this tutorial, you’ll know:

  • What infinite scrolling pagination is
  • What its alternatives are
  • Why it’s such a big deal
  • How to go from a non-paginated app to a paginated one
  • How to take that knowledge to any project you work on

Getting Started

Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial.

In case you didn’t know, raywenderlich.com has an app for Android and iOS called (drum roll, please): raywenderlich. The thing is, that one is for videos. Today you’ll be working on a low budget version for articles: readwenderlich!

Unzip the downloaded file and open Android Studio 4.1 or later. You can use Visual Studio Code instead, but you might need to tweak some instructions to follow along.

Click on Open an existing Android Studio project and choose the starter folder from your unzipped download.

Now, download your dependencies by double-clicking pubspec.yaml on the left-side panel (1) and then clicking Pub get (2) at the top of your screen.

Instructions on downloading pubspec.yaml dependencies.

Finally, build and run. If everything went OK, you should see something like this:

Starter version of the sample project.

The starter project only fetches the first 20 items for the filtering and sorting options you set. For example, if you filter by Flutter and sort by Most Popular, you’ll see the 20 most popular Flutter articles.

Diving Into the Code

There are many files in the project, but the ones you need to be familiar with are:

  1. lib/ui/preferences/list_preferences.dart: A plain Dart class gathering all the filtering and sorting options the user selected.
  2. lib/ui/list/article_list_view.dart: A widget that receives and uses its information to fetch and display a list of articles. The image below highlights the exact part of the screen controlled by this widget.

ArticleListView widget highlighted on the sample project.

The starter project’s state management approach is setState, because that’s the neutral ground for all Flutter developers. But what you’ll learn here applies to any strategy.

Throughout the tutorial, you won’t change . Instead, you’ll write a substitute for it from scratch.

Rather than a top 20, you want readwenderlich to be a complete catalog of all the articles on raywenderlich.com. For that, you’ll rely on infinite scrolling pagination.

Understanding Pagination

Two guys walk into a bar… just kidding! It’s actually one person, and it’s a woman. You’ll call her the user, while the bar is your app.

The night is just beginning, and you, the bartender, know the user will consume lots of data drinks. What you don’t yet know is how many.

You’re committed to providing the best customer experience, so you start wondering what would be the optimal way of serving your user. You then grab some nearby napkins and start writing out your options:

Napkin sketch of an eager way of serving drinks.

If you think of drinks like batches of items in a list — the so-called pages — the method above is how non-paginated apps work. It’s no surprise that there aren’t bars that serve like this, but unfortunately, this is how most apps work. Which leads you to another option:

Napkin sketch of the conventional lazy way of serving drinks.

If you’re familiar with the above, don’t worry. It’s not only because you’ve been going a lot to bars, but also because that’s how good old web-like pagination works:

Page selection bar from Google Search.

Every time you finish a page, you have to manually ask for another. Good, but still not perfect. It’d be better if you could automate the process.

Automating Pagination

With no luck on your quest for the holy grail of drink service, you’re considering settling for the conventional way… until the customer comes to you with a fantastic idea:

Woman asking a bartender to hand her a drink any time she's lacking one.

That sounds amazing! But you’re cautious, and you don’t want to make a decision before planning everything out on paper a napkin:

Napkin sketch of an automated way of serving drinks.

It’s a done deal! Thank goodness; that was your last napkin!

Luckily, someone did science a favor and recorded the experiment:

Bartender actively serving drinks every time the customer is without one.

This process is the same as infinite scrolling pagination: As the user scrolls down your screen, you watch what’s going on and fetch more data before she hits the bottom of the screen, giving her the smooth experience of scrolling an infinite list.

Look, all the cool kids apps are doing it:

Twitter, Facebook and Instagram using infinite scrolling pagination.

So now that you know what you’ll be doing, it’s time to roll up your sleeves.

Creating a Paginated ArticleListView

Start off by creating a new file inside lib/ui/list called paged_article_list_view.dart. Put the following inside the file:

import 'package:flutter/material.dart'; import 'package:readwenderlich/data/repository.dart'; import 'package:readwenderlich/entities/article.dart'; import 'package:readwenderlich/ui/exception_indicators/empty_list_indicator.dart'; import 'package:readwenderlich/ui/exception_indicators/error_indicator.dart'; import 'package:readwenderlich/ui/list/article_list_item.dart'; import 'package:readwenderlich/ui/preferences/list_preferences.dart'; // 1 class PagedArticleListView extends StatefulWidget { const PagedArticleListView({ // 2 @required this.repository, // 3 this.listPreferences, Key key, }) : assert(repository != null), super(key: key); final Repository repository; final ListPreferences listPreferences; @override _PagedArticleListViewState createState() => _PagedArticleListViewState(); } class _PagedArticleListViewState extends State<PagedArticleListView> { // 4 ListPreferences get _listPreferences => widget.listPreferences; // TODO: Instantiate a PagingController. @override // 5 Widget build(BuildContext context) => const Placeholder(); }

Here’s what you just did:

  1. This is the widget that will replace the old non-paginated list onscreen. This is your paginated version of .
  2. You’re asking a instance from the enclosing widget. comes with the starter project and helps you communicate with the remote API.
  3. Similarly, you’re now asking a instance from the enclosing widget.
  4. You’re creating a computed property to help you access the received in the previous step without the need to type every time.
  5. The fills the screen with a giant X while you don’t have the paginated list widget figured out yet. You’ll get back to this shortly.

Now you need to be able to visualize what you just created.

Swapping List Widgets

Swap the old for your fresh . For that, open lib/ui/list/article_list_screen.dart and add an import to your new file at the top:

import 'package:readwenderlich/ui/list/paged_article_list_view.dart';

Since you’re already working with the imports, take the opportunity to do some cleaning by removing the soon-to-be unused import:

import 'package:readwenderlich/ui/list/article_list_view.dart';

Jump to the and replace the ‘s property with:

body: PagedArticleListView( repository: Provider.of<Repository>(context), listPreferences: _listPreferences, ),

You’re obtaining a instance from , your dependency injection system for this project.

That’s it! You can delete the now obsolete lib/ui/list/article_list_view.dart.

Build and run. You should see your in action:

Intermediate version of the sample project, displaying a placeholder instead of the list.

Engineering Infinite Scrolling Pagination

In the whole drink service situation above, you looked at infinite scrolling pagination from a product perspective. Now, put your developer glasses on, divide your goal into pieces and examine what it takes to conquer it:

  • Watch the user’s scroll position so that you can fetch other pages in advance.
  • Keep track of and transition between every possible status in your list.
  • Flow diagram of all possible listing statuses.

  • Keep the user posted by displaying indicators for each different status.
  • Screenshots of every possible pagination status.

  • Make a solution that’s reusable in different screens, possibly using other layouts. One example of this is grids. Ideally, this solution should also be portable to different projects with other state management approaches.

Sounds like hard work? It doesn’t have to be. These issues are already addressed by the Infinite Scroll Pagination package, which will be your companion for this article. In the next section, you’ll take a closer look at this package.

Getting to Know the Package

Warm up by opening pubspec.yaml and replacing with :

dependencies: flutter: sdk: flutter infinite_scroll_pagination: ^3.1.0

Download your newest dependency by clicking on Pub get in the Flutter commands bar at the top of your screen.

The Infinite Scroll Pagination package makes your job as easy as stealing candy from a baby, shooting fish in a barrel or assembling a three-piece jigsaw puzzle. Speaking of the latter, here’s your first piece:

PagingController represented as a puzzle piece.

is a controller for paged widgets. It’s responsible for holding the current state of the pagination and request pages from its listeners whenever needed.

If you’ve worked with Flutter’s TextEditingController or ScrollController, for example, you’ll feel at home with .

Instantiating a PagingController

Back to lib/ui/list/paged_article_list_view.dart, add an import to the new library at the top of the file:

import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';

Now, replace with:

// 1 final _pagingController = PagingController<int, Article>( // 2 firstPageKey: 1, ); @override void initState() { // 3 _pagingController.addPageRequestListener((pageKey) { _fetchPage(pageKey); }); super.initState(); } Future<void> _fetchPage(int pageKey) async { // TODO: Implement the function's body. } @override void dispose() { // 4 _pagingController.dispose(); super.dispose(); }

Here’s a step-by-step explanation of what the code above does:

  1. When instantiating a , you need to specify two generic types. In your code, they are:
    • : This is the type your endpoint uses to identify pages. For the raywenderlich.com API, that’s the page number. For other APIs, instead of a page number, that could be a token or the number of items to offset. Due to this diversity of pagination strategies, the package calls these identifiers page keys.
    • : This is the type that models your list items.
  2. Remember the you specified as a generic type in the previous step? Now you need to provide its initial value by using the parameter. For the raywenderlich.com API, page keys start at , but other APIs might start at .
  3. This is how you register a callback to listen for new page requests.
  4. Don’t forget to your controller.

Fetching Pages

Your implementation doesn’t have much use as it is right now. Fix this by replacing the entire function with:

Future<void> _fetchPage(int pageKey) async { try { final newPage = await widget.repository.getArticleListPage( number: pageKey, size: 8, // 1 filteredPlatformIds: _listPreferences?.filteredPlatformIds, filteredDifficulties: _listPreferences?.filteredDifficulties, filteredCategoryIds: _listPreferences?.filteredCategoryIds, sortMethod: _listPreferences?.sortMethod, ); final previouslyFetchedItemsCount = // 2 _pagingController.itemList?.length ?? 0; final isLastPage = newPage.isLastPage(previouslyFetchedItemsCount); final newItems = newPage.itemList; if (isLastPage) { // 3 _pagingController.appendLastPage(newItems); } else { final nextPageKey = pageKey + 1; _pagingController.appendPage(newItems, nextPageKey); } } catch (error) { // 4 _pagingController.error = error; } }

This is where all the magic happens:

  1. You’re forwarding the current filtering and sorting options to the repository.
  2. is a property of . It holds all items loaded so far. You’re using the conditional property access because initial value is .
  3. Once you have your new items, let the controller know by calling or on it.
  4. If an error occurred, supply it to the controller’s property.

Build and run to make sure you haven’t introduced any errors. Don’t expect any visual or functional changes.

Intermediate version of the sample project, displaying a placeholder instead of the list.

Using a Paginated ListView

Before you move on to the , there’s something you need to know:

PagingController and PagedListView represented as puzzle pieces.

The second piece is exactly what its name suggests: a paginated version of a regular . And as the illustration shows, it’s in there that you’ll fit in your controller.

Still on lib/ui/list/paged_article_list_view.dart, replace the old with:

@override Widget build(BuildContext context) => // 1 RefreshIndicator( onRefresh: () => Future.sync( // 2 () => _pagingController.refresh(), ), // 3 child: PagedListView.separated( // 4 pagingController: _pagingController, padding: const EdgeInsets.all(16), separatorBuilder: (context, index) => const SizedBox( height: 16, ), ), );

Here’s what’s going on:

  1. Wrapping scrollable widgets with Flutter’s empowers a feature known as swipe to refresh. The user can use this to refresh the list by pulling it down from the top.
  2. defines , a function for refreshing its data. You’re wrapping the call in a , because that’s how the parameter from the expects it.
  3. Like the good old you already know, has an alternative constructor for adding separators between your list items.
  4. You’re connecting your puzzle pieces.

Building List Items

After all this, you suspect something might be wrong — after all, what’s going to build your list items?

The good Sherlock Holmes that you are, you investigate by hovering your magnifying glass — also known as a mouse — over :

Android Studio warning about a missing required parameter.

Well done, detective. You found the missing puzzle piece!

PagingController, PagedListView and PagedChildBuilderDelegate represented as puzzle pieces.

Now, it’s time to put them all together!

Creating a Builder Delegate

For the final touch, fill that same gap in code by specifying this new parameter to your , in the same level as , and :

builderDelegate: PagedChildBuilderDelegate<Article>( itemBuilder: (context, article, index) => ArticleListItem( article: article, ), firstPageErrorIndicatorBuilder: (context) => ErrorIndicator( error: _pagingController.error, onTryAgain: () => _pagingController.refresh(), ), noItemsFoundIndicatorBuilder: (context) => EmptyListIndicator(), ),

is a collection of builders for every widget involved in infinite scrolling pagination.

Although you’ve only specified three parameters in your code, knowing all seven of them might save you in the future:

  • : This builds your list items. It’s the only required parameter; all others have defaults.
  • : This builds a widget that informs the user the occurrence of an error fetching the first page. In this scenario, you won’t yet have any list items loaded, so you’ll want this widget to fill the entire space. Make sure you call on your controller if you decide to add a retry button to your indicator — take another look at the previous code snippet and you’ll see it.
  • : This also indicates an error, but for subsequent page requests. As you already have some items loaded, the widget you build here appears at the bottom of your list. If you add a retry button to your indicator, make sure you call on your controller when the user taps your button.
  • : This builds the widget that’ll show while loading the first page. You won’t yet have any items loaded, so you’ll want this widget to fill the entire space.
  • : This is similar to the previous builder, but it shows while loading subsequent pages. As you already have some items loaded, the widget you build here appears at the bottom of your list.
  • : What if your API successfully returns an empty list? Technically that’s not an error, and it’s usually associated with too many filter options selected. The widget you build here covers this “zero items” scenario.
  • : Here it is, the gold at the end of the rainbow! This is where you optionally build a widget to display when the user finally reaches the end of your list. Mystery solved!

Build and run. Try turning off your device’s connection and using swipe to refresh as shown in the GIF below. This will help you test both and the custom error indicator widget.

Sample project with filters not working properly.

Hmm, there’s a bug in your app. Apparently that wasn’t the final touch after all. Try figuring out what’s wrong. If you’re stuck, click the Reveal button below to find out what it is.

[spoiler title=”Filters Bug”]
Applying filters doesn’t seem to be taking any effect.
[/spoiler]

Applying Filters

You know what they say: Be suspicious if your code works on the first try. Well, yours didn’t, so you’re probably doing something right!

Here’s what’s causing the bug: When the user applies filters, rebuilds your with a brand-new , but no one warned your about the change.

The place for solving this is lib/ui/list/paged_article_list_view.dart. Inside , add the following function override:

@override void didUpdateWidget(PagedArticleListView oldWidget) { if (oldWidget.listPreferences != widget.listPreferences) { _pagingController.refresh(); } super.didUpdateWidget(oldWidget); }

This is what the code above is saying: Whenever the widget associated with this subclass updates, if the also changed, refresh the by calling on it.

Mission accomplished. Time to build and run readwenderlich for the last time and allow the wonder of infinite scrolling pagination to amaze you. You did it!

Completed sample project.

Where to Go From Here?

Download the completed project files by clicking the Download Materials button at the top or bottom of the tutorial.

Now for the coolest part: The Infinite Scroll Pagination package comes with replacement parts for your middle piece. Choose whichever suits your next layout the best.

All classes from the Infinite Scroll Pagination package represented as jigsaw puzzle pieces.

You can find more details on these extra pieces in the package’s cookbook.

Here’s a suggestion: The endpoint you used to fetch your articles accepts search queries. How about using that to add search support to readwenderlich?

We hope you enjoyed this tutorial. If you have any questions or comments, please join the forum discussion below!

raywenderlich.com Weekly

The raywenderlich.com newsletter is the easiest way to stay up-to-date on everything you need to know as a mobile developer.

Get a weekly digest of our tutorials and courses, and receive a free in-depth email course as a bonus!

Sours: https://www.raywenderlich.com/14214369-infinite-scrolling-pagination-in-flutter

You will also like:

Chapter 9. Async Dart and Flutter and infinite scrolling

  • Futures in Dart
  • Streams and sinks in Dart
  • Async builder in Flutter
  • Slivers and scrollable widgets
  • Scroll physics

This chapter could contain the most difficult concepts to wrap your head around, unless you’re familiar with async UI programming. The beginning of this chapter is only about asynchronous concepts and implementing them in Dart. After that, I examine how those concepts are useful in Flutter.

Note

If you’re okay with the following code listing, then you should skip to section 9.2, where we begin the Flutter portion.

Listing 9.1. Example Dart code using streams and sinks
// Streams and Sinks StreamController<bool> _controller = StreamController<bool>(); Stream get onEvent => _controller.stream; void handleEvent() { onEvent.listen((val) => print(val)); } // async / await void getRequest() async { var response = await http.get(url); return response; }

If you aren’t comfortable with this listing, then strap in. Async programming is mandatory in modern UIs, but it can be difficult to grok at first.

Dart programming makes heavy use of a specific async pattern, which is known in many languages as observables. (Observables are also the foundational concept of Rx libraries.) In Dart, observables are called streams. You won’t get very far into any Dart code before you have to start dealing with streams. And, in fact, I’d claim they’re necessary for effective Flutter programming.

9.1. Async Dart

9.1.1. Future recap

9.1.2. The async/await keywords

9.1.3. Catching errors with futures

9.1.4. Catching errors with try and catch

9.2. Sinks and streams (and StreamControllers)

9.2.1. Anatomy of the observer pattern with Dart streams

9.2.2. Implementing streams

9.2.3. Broadcasting streams

9.2.4. Higher-order streams

9.3. Using streams in blocs

9.3.1. Blocs use inputs and outputs

9.3.2. Implementing a bloc input

9.4. Async Flutter: StreamBuilder

9.5. Infinite and custom scrollable widgets

9.5.1. CustomScrollView and slivers

9.5.2. Catalog widget scroll view

9.5.3. The SliverGrid widget

9.5.4. Delegates

9.5.5. Custom slivers

Sours: https://livebook.manning.com/book/flutter-in-action/chapter-9/


754 755 756 757 758