scroll_snap_list 0.3.0

scroll_snap_list #

A wrapper for ListView.builder widget that allows "snaping" event to an item at the end of user-scroll.

This widget allows unrestricted scrolling (unlike other widget that only able to "snap" to left/right neighbor at a time).

  • Support horizontal & vertical list
  • Use ListView.Builder, means no Animation

You can use this widget to achieve:

  • Unrestricted scrollable Jumbotron
  • Show daily entry for Health App and shows its detail directly below the list (reduce number of click)
  • Scrollable InputSelect, like datetime picker in cupertino
Jumbotron ListHorizontal ListVertical List
Horizontal Jumbotron ListHorizontal List with infinite-loadingVertical list with InkWell ListItems

Getting Started #

In your flutter project pubspec.yaml add the dependency:

dependencies:
  ...
  scroll_snap_list: ^0.3.0

Usage example #

This library doesn't use other library, so it should work out of the box.

Import scroll_snap_list.dart.

import 'package:scroll_snap_list/scroll_snap_list.dart';

Add ScrollSnapList in your build method. Make sure to enter correct itemSize (helps with "snapping" process).

Expanded(
  child: ScrollSnapList(
    onItemFocus: _onItemFocus,
    itemSize: 35,
    itemBuilder: _buildListItem,
    itemCount: data.length,
    reverse: true,
  ),
),

Full example:

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:scroll_snap_list/scroll_snap_list.dart';

void main() => runApp(HorizontalListDemo());

class HorizontalListDemo extends StatefulWidget {
  @override
  _HorizontalListDemoState createState() => _HorizontalListDemoState();
}

class _HorizontalListDemoState extends State<HorizontalListDemo> {
  List<int> data = [];
  int _focusedIndex = 0;

  @override
  void initState() {
    super.initState();

    for (int i = 0; i < 30; i++) {
      data.add(Random().nextInt(100) + 1);
    }
  }

  void _onItemFocus(int index) {
    setState(() {
      _focusedIndex = index;
    });
  }

  Widget _buildItemDetail() {
    if (data.length > _focusedIndex)
      return Container(
        height: 150,
        child: Text("index $_focusedIndex: ${data[_focusedIndex]}"),
      );

    return Container(
      height: 150,
      child: Text("No Data"),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    //horizontal
    return Container(
      width: 35,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Container(
            height: data[index].toDouble()*2,
            width: 25,
            color: Colors.lightBlueAccent,
            child: Text("i:$index\n${data[index]}"),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Horizontal List Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text("Horizontal List"),
        ),
        body: Container(
          child: Column(
            children: <Widget>[
              Expanded(
                child: ScrollSnapList(
                  onItemFocus: _onItemFocus,
                  itemSize: 35,
                  itemBuilder: _buildListItem,
                  itemCount: data.length,
                  reverse: true,
                ),
              ),
              _buildItemDetail(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  RaisedButton(
                    child: Text("Add Item"),
                    onPressed: () {
                      setState(() {
                        data.add(Random().nextInt(100) + 1);
                      });
                    },
                  ),
                  RaisedButton(
                    child: Text("Remove Item"),
                    onPressed: () {
                      int index = data.length > 1
                          ? Random().nextInt(data.length - 1)
                          : 0;
                      setState(() {
                        data.removeAt(index);
                      });
                    },
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

Important parameters and explanation #

ParameterExplanation
itemBuilderSame as ListView's itemBuilder
curveAnimation curve when snapping
durationAnimation duration
endOfListTolerancePixel tolerance to trigger onReachEnd
focusOnItemTapFocus to an item when user tap on it. Inactive if the list-item have its own onTap detector (use state-key to help focusing instead).
focusToItemMethod to manually trigger focus to an item. Call with help of GlobalKey<ScrollSnapListState>
marginContainer's margin
itemCountNumber of item in this list
itemSizeSize used is width if scrollDirection is Axis.horizontal, height if Axis.vertical. Composed of the size of each item + its margin/padding.
onItemFocusCallback function when list snaps/focuses to an item
onReachEndCallback function when user reach end of list. E.g. load more data from db
reverseSame as ListView's reverse to reverse scrollDirection
updateOnScrollCalls onItemFocus (if it exists) when ScrollUpdateNotification fires
initialIndexOptional initial position which will not snap until after the first drag
scrollDirectionListView's scrollDirection
listControllerExternal ScrollController

Other Notice #

By default, SnapScrollList set focusOnItemTap as true. Means any tap event on items will trigger snap/focus event to that item.

This behavior use GestureDetector, so if the list's items have their own detector (e.g. InkWell, Button), SnapScrollList unable to trigger snap event on its own. To handle this, we may use GlobalKey<ScrollSnapListState> to trigger the event manually.

Add GlobalKey<ScrollSnapListState> in your widget

GlobalKey<ScrollSnapListState> sslKey = GlobalKey();

Add key parameter to SnapScrollList.

ScrollSnapList(
  onItemFocus: _onItemFocus,
  itemSize: 50,
  itemBuilder: _buildListItem,
  itemCount: data.length,
  key: sslKey,
  scrollDirection: Axis.vertical,
)

In your buildItem method, call focusToItem method.

Widget _buildListItem(BuildContext context, int index) {
  //horizontal
  return Container(
    height: 50,
    child: Material(
      color: _focusedIndex == index ? Colors.lightBlueAccent : Colors.white,
      child: InkWell(
        child: Text("Index: $index | Value: ${data[index]}"),
        onTap: () {
          print("Do anything here");

          //trigger focus manually
          sslKey.currentState.focusToItem(index);
        },
      ),
    ),
  );
}

Full example for this part can be found in example/vertical_list.dart.

[0.3.0]

  • Added updateOnScroll and initial value (value before first snap) (Thanks @hawkinsjb1 !)
  • Added checking to avoid multiple onItemFocus call for the same index
  • Updated method to handle isInit (delayed instead of one trigger)

[0.2.1]

  • Updated horizontal_list sample to include simulated data loading
  • Added endOfListTolerance to determine end-of-list position (which trigger onReachEnd)

[0.2.0]

  • Fix bug sometimes scrolling stuck at the end of listview
  • Breaking: Changed buildItemList parameter to itemBuilder

[0.1.3]

  • Updated readme

[0.1.2]

  • Added Horizontal Jumbotron List demo

[0.1.1]

  • Minor update description

[0.1.0] - First release

  • First release

example/README.md

Examples #

Usage: Copy-paste the codes into a new Flutter Project (e.g. in main.dart), then run them.

Horizontal Jumbotron #

Simple horizontal jumbotron from left to right.

Horizontal List #

Horizontal right to left list with simulated "loading from DB" data. Often used in Health Apps.

Vertical List #

Simple InputSelect UI. Similar to Cupertino's InputSelect.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  scroll_snap_list: ^0.3.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:scroll_snap_list/scroll_snap_list.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
60
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
80
Learn more about scoring.

We analyzed this package on Feb 21, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.5
  • Flutter: 1.12.13+hotfix.7

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test