Giter Site home page Giter Site logo

the-ring-io / flutter_staggered_animations Goto Github PK

View Code? Open in Web Editor NEW
1.6K 17.0 134.0 962 KB

Easily add staggered animations to your ListView, GridView, Column and Row children.

License: MIT License

Dart 98.02% Kotlin 0.46% Swift 1.39% Objective-C 0.13%

flutter_staggered_animations's Introduction

Pub

Flutter Staggered Animations

Easily add staggered animations to your ListView, GridView, Column and Row children as shown in Material Design guidelines

Showcase

ListView GridView Column

Flutter 3.0 and breaking changes

Starting version 1.1.0 flutter_staggered_animations requires Dart SDK 2.17 minimum. If you want to keep using flutter_staggered_animations but cannot migrate to Dart SDK 2.17 yet, use the version 1.0.0 instead.

Flutter 2.0 and null-safety

From 1.0.0 and onwards, flutter_staggered_animations is null-safe and requires Dart SDK 2.12.0 minimum. If you want to keep using flutter_staggered_animations but cannot migrate to null-safety yet, use the version 0.1.3 instead.

Installation

Dependency

Add the package as a dependency in your pubspec.yaml file.

dependencies:
  flutter_staggered_animations: ^1.0.0

Import

Import the package in your code file.

import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';

Basic usage

Here is a sample code to apply a staggered animation on ListView items.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: AnimationLimiter(
      child: ListView.builder(
        itemCount: 100,
        itemBuilder: (BuildContext context, int index) {
          return AnimationConfiguration.staggeredList(
            position: index,
            duration: const Duration(milliseconds: 375),
            child: SlideAnimation(
              verticalOffset: 50.0,
              child: FadeInAnimation(
                child: YourListChild(),
              ),
            ),
          );
        },
      ),
    ),
  );
}

API Overview

This package contains three type of classes:

  • Animation
  • AnimationConfiguration
  • AnimationLimiter

Animations

Animations are split into 4 classes:

  • FadeInAnimation
  • SlideAnimation
  • ScaleAnimation
  • FlipAnimation

Animations can be composed to produce advanced animations effects by wrapping them.

Example of a SlideAnimation combined with a FadeInAnimation:

child: SlideAnimation(
  verticalOffset: 50.0,
    child: FadeInAnimation(
      child: YourListChild(),
    ),
)

Animations must be direct children of AnimationConfiguration.

AnimationConfiguration

AnimationConfiguration is an InheritedWidget that shares its animation settings with its children (mainly duration and delay).

Named constructors

Depending on the scenario in which you will present your animations, you should use one of AnimationConfiguration's named constructors.

  • AnimationConfiguration.synchronized if you want to launch all children's animations at the same time.
  • AnimationConfiguration.staggeredList if you want to delay the animation of each child to produce a single-axis staggered animations (from top to bottom or from left to right).
  • AnimationConfiguration.staggeredGrid if you want to delay the animation of each child to produce a dual-axis staggered animations (from left to right and top to bottom).

If you're not in the context of a ListView or GridView, an utility static method is available to help you apply staggered animations to the children of a Row or Column:

  • AnimationConfiguration.toStaggeredList

You can override duration and delay in each child Animation if needed.

AnimationLimiter

In the context of a scrollable view, your children's animations are only built when the user scrolls and they appear on the screen. This create a situation where your animations will be run as you scroll through the content. If this is not a behaviour you want in your app, you can use AnimationLimiter.

AnimationLimiter is an InheritedWidget that prevents the children widgets to be animated if they don't appear in the first frame where AnimationLimiter is built.

To be effective, AnimationLimiter must be a direct parent of your scrollable list of widgets.

You can omit AnimationLimiter if your view is not scrollable.

Quick samples

ListView

Here is a sample code to apply a staggered animation on the children of a ListView.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: AnimationLimiter(
      child: ListView.builder(
        itemCount: 100,
        itemBuilder: (BuildContext context, int index) {
          return AnimationConfiguration.staggeredList(
            position: index,
            duration: const Duration(milliseconds: 375),
            child: SlideAnimation(
              verticalOffset: 50.0,
              child: FadeInAnimation(
                child: YourListChild(),
              ),
            ),
          );
        },
      ),
    ),
  );
}

GridView

Here is a sample code to apply a staggered animation on the children of a GridView.

@override
Widget build(BuildContext context) {
  int columnCount = 3;

  return Scaffold(
    body: AnimationLimiter(
      child: GridView.count(
        crossAxisCount: columnCount,
        children: List.generate(
          100,
          (int index) {
            return AnimationConfiguration.staggeredGrid(
              position: index,
              duration: const Duration(milliseconds: 375),
              columnCount: columnCount,
              child: ScaleAnimation(
                child: FadeInAnimation(
                  child: YourListChild(),
                ),
              ),
            );
          },
        ),
      ),
    ),
  );
}

Column

Here is a sample code to apply a staggered animation on the children of a Column.

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: AnimationLimiter(
          child: Column(
            children: AnimationConfiguration.toStaggeredList(
              duration: const Duration(milliseconds: 375),
              childAnimationBuilder: (widget) => SlideAnimation(
                horizontalOffset: 50.0,
                child: FadeInAnimation(
                  child: widget,
                ),
              ),
              children: YourColumnChildren(),
            ),
          ),
        ),
      ),
    );
  }

License

Flutter Staggered Animations is released under the MIT License

About us

As of July 2022, this package is maintained by the front team working on the french mobile application Dailyn

flutter_staggered_animations's People

Contributors

callmesh avatar cybernetics354 avatar danger-ahead avatar furaiev avatar josh-burton avatar miiite avatar nilsreichardt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flutter_staggered_animations's Issues

Migrate example to Android embedding v2

Description

The example of this package isn't migrated to Android embedding v2 yet.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Warning
──────────────────────────────────────────────────────────────────────────────
Your Flutter application is created using an older version of the Android
embedding. It's being deprecated in favor of Android embedding v2. Follow the
steps at

https://flutter.dev/go/android-project-migration

to migrate your project.

Steps to reproduce

  1. Open example
  2. Run flutter pub get

How can i apply slide navigation to listView items.

Hi
Basically i have simply screen with 1 question and dynamic answers and for that i have uses 1 text and ListView for dynamic answers so i want to animate question answers from right to left.

1st question ==> all answers animate from right to left.
2nd question ==> all answers animate from right to left.

I have do the below but it animate always 1st time. Animation not applied for rest of the questions answers listview.

return AnimationLimiter(
      child: ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        itemCount: answers!.answers![queCount].options!.length,
        itemBuilder: (ctx, i) {
          return AnimationConfiguration.staggeredList(
            position: i,
            duration: const Duration(milliseconds: 1000),
            child: SlideAnimation(
              horizontalOffset: 500.0,
              child: Container(
                margin: const EdgeInsets.symmetric(vertical: 8),
                padding: const EdgeInsets.all(12),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  gradient: answers!.answers![queCount].options![i].checked!
                      ? const RadialGradient(
                          center: Alignment(-0.8, -0.6),
                          colors: [
                            Color.fromRGBO(0, 174, 239, 0.22),
                            Color.fromRGBO(0, 174, 239, 0)
                          ],
                          radius: 4.8,
                        )
                      : null,
                  border: Border.all(color: ColorCodes.blueColor, width: 1),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  answers!.answers![queCount].options![i].name ?? "",
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          );
        },
      ),
    );

How can i apply effect for all question answers?

Sequential variant for StaggeredGrid

Instead of animating widgets by diagonal lines in a grid, I'd like to be able to animate each item in the grid sequentially in reading order: from left to right (or right to left, for RTL locales), then top to bottom.

Would it be possible to add this variant?

WidgetsBinding warnings after upgrading to Flutter 3.0

After upgrading to latest Flutter release 3.0, some warnings started appearing in the console logs. Hopefully these are only warnings.

: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
../…/src/animation_limiter.dart:43
- 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('../../flutter/packages/flutter/lib/src/widgets/binding.dart').
package:flutter/…/widgets/binding.dart:1
    WidgetsBinding.instance!.addPostFrameCallback((Duration value) {

The error is generated from line https://github.com/mobiten/flutter_staggered_animations/blob/780941c20a088d8314c2e5a141bd2215ea294738/lib/src/animation_limiter.dart#L43

Issue with OpenContainer

Will return

Another exception was thrown: Animation not wrapped in an AnimationConfiguration.

if used within an OpenContainer, and then click on object of that list.
Here is my code

AnimationLimiter(
        child: ListView.separated(
          //...
          itemBuilder: (context, index) => AnimationConfiguration.staggeredList(
            position: index,
            duration: Duration(milliseconds: 400),
            child: OpenContainer(
               //...
              openBuilder: (context, _) => ProductPage(
                product: Product.products[index],
              ),
              closedBuilder: (context, VoidCallback openContainer) =>
                  SlideAnimation(
                horizontalOffset: 500.w,
                child: Container(
                  //...
                  child: GestureDetector(
                     //...
                    child: ProductWidget(
                      product: Product.products[index],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ),

Animated Limiter Issue in Flutter Web

Issue: NoSuchMethodError: invalid member on null: 'dependOnInheritedWidgetOfExactType'

AnimatedLimiter(
child: InkWell(
child: Widget,
onPressed(){
Scrollable.ensureVisible(
key.currentContext,
duration: Duration(milliseconds: 1500),
);
}
)
) ;

P.S. No issue in app

Animations on Remove item

Hi, thanks for such an amazing package, I've been using this a lot.

Is there any way to handle animations when an item is remove from the list?

Broken in Flutter version 2.0.0

../../../../../../SDK/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_staggered_animations-0.1.2/lib/src/animation_configuration.dart:161:20: Error: The method 'ancestorWidgetOfExactType' isn't defined for the cl
ass 'BuildContext'.

  • 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../../../../SDK/flutter/packages/flutter/lib/src/widgets/framework.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
    return context.ancestorWidgetOfExactType(AnimationConfiguration)
    ^^^^^^^^^^^^^^^^^^^^^^^^^
    ../../../../../../SDK/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_staggered_animations-0.1.2/lib/src/animation_limiter.dart:75:20: Error: The method 'ancestorWidgetOfExactType' isn't defined for the class 'Bu
    ildContext'.
  • 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../../../../SDK/flutter/packages/flutter/lib/src/widgets/framework.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
    return context.ancestorWidgetOfExactType(_AnimationLimiterProvider)
    ^^^^^^^^^^^^^^^^^^^^^^^^^

Update pub.dev

Can you please update the version on pub.dev to match GitHub?

Animation does not work in FutureBuilder

Maybe it's something I'm doing on my end, but I couldn't get it to work on list inside a FutureBuilder
Apologies for the indentation :)

return ListView.builder(
                            itemCount: items.length + 1,
                            itemBuilder: (context, index) {
                              if (index == 0) {
                                return Container(
                                  margin: EdgeInsets.all(10),
                                  padding: EdgeInsets.all(7),
                                  child: Row(
                                    children: [
                                      Text('Number'),
                                      Text('Name'),
                                      Text('Price')
                                    ],
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                  ),
                                );
                              }
                              index--;
                              final currentItem = items[index];

                              return AnimationConfiguration.staggeredList(
                                position: index,
                                duration: const Duration(milliseconds: 400),
                                child: SlideAnimation(
                                  verticalOffset: 50,
                                  horizontalOffset: 100,
                                  child: FadeInAnimation(
                                    child: Card(
                                      child: ListTile(
                                        leading: Text('${index + 1}'),
                                        title: Center(
                                            child: Text(currentItem['name'])),
                                        subtitle: Center(
                                            child: Text(
                                                '''Bought ${currentItem["count"]} times for a total of ${currentItem['price'] * currentItem["count"]} dirhams''')),
                                        trailing:
                                            Text('${currentItem["price"]} Dhs'),
                                      ),
                                    ),
                                  ),
                                ),
                              );
                            },
                          );

Using Spacer in toStaggeredList gives error.

Description

When I want to animate a Column using AnimationConfiguration.toStaggeredList as referred to in the readme, Flutter throws an error.

Problem

I do not know that neither flutter_staggered_animations nor Flutter are capable or designed to animate an Expanded widget but I cannot use Spacer in the Column when I want to animate widgets inside the column.

Error Code

Exception has occurred. FlutterError (Incorrect use of ParentDataWidget. The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData. Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets. The offending Expanded is currently placed inside a Transform widget. The ownership chain for the RenderObject that received the incompatible parent data was: sized box.shrink ← Expanded ← Spacer ← Transform ← AnimatedBuilder ← AnimationExecutor ← AnimationConfigurator ← SlideAnimation ← AnimationConfiguration ← Column ← ⋯)

The Code Shortly

return Column(
                children: [
                  Expanded(
                    child: Card(
                      margin:
                          EdgeInsets.only(left: 5, top: 5, right: 5, bottom: 0),
                      child: AnimationLimiter(child: Column(
                        children: AnimationConfiguration.toStaggeredList(
                          duration: Duration(milliseconds: 175),
                          childAnimationBuilder: (widget) => SlideAnimation(
                              horizontalOffset: 50, child: widget),
                          children: [
                            ...
                            Divider(
                              thickness: 2,
                              height: 10,
                            ),
                            SizedBox(
                              height: 15,
                            ),
                            SwitchListTile(
                              title: Row(
                                children: [
                                  Text(
                                    'Theme: ',
                                    style: TextStyle(color: Colors.black54),
                                  ),
                                  Text(
                                    lightMode ? 'Sun' : 'Moon',
                                    style: TextStyle(
                                      color: lightMode
                                          ? Colors.amber[300]
                                          : Colors.black,
                                    ),
                                  ),
                                  TextButton(
                                    onPressed: () {},
                                    style: ButtonStyle(
                                        alignment: Alignment.centerLeft,
                                        padding: MaterialStateProperty.all<
                                            EdgeInsets>(EdgeInsets.zero)),
                                    child: Text('Sync with system'),
                                  ),
                                ],
                              ),
                              value: lightMode,
                              onChanged: (state) async {},
                            ),
                            Spacer(),<-- Causes error.
                            GestureDetector(...

image

So, for a solution, what can we do? How I can exclude Spacer or make space there?

The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.

../../../../../flutter/.pub-cache/hosted/pub.dartlang.org/flutter_staggered_animations-0.1.2/lib/src/animation_configuration.dart:161:20: Error: The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.

  • 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../../../flutter/packages/flutter/lib/src/widgets/framework.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
    return context.ancestorWidgetOfExactType(AnimationConfiguration)
    ^^^^^^^^^^^^^^^^^^^^^^^^^

Seems to be deprecated on master.

https://stackoverflow.com/questions/65657716/error-the-method-ancestorstateoftype-isnt-defined-for-the-class-buildcontex

Guidance with using staggered animations with SliverList

Is it possible to use this library with a SliverList? I'm afraid I haven't seen this use case in the docs.
Here is the code I want to wrap:

  return SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    List<MbTransaction> mbTransaction =
                        snapshot.data.mbTransactions;

                    return TransEnqListTile(
                      transaction: mbTransaction[index],
                      color: double.parse(mbTransaction[index].amount) > 0
                          ? Color(0xff07B226)
                          : Color(0xffE41F0D),
                    );
                  },
                  childCount: snapshot.data.mbTransactions.length,
                ),
              );

there is runtime error i cant solve it plz look at it if you can

here is my code

AnimationLimiter(
                key: UniqueKey(),
                child: StreamBuilder(
                  stream: ref
                      .doc(_auth.currentUser!.uid)
                      .collection('notes')
                      .snapshots(),
                  builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (snapshot.hasError) {
                      return const Center(
                        child: Text('SomeThing went Wrong'),
                      );
                    }
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      const Center(
                        child: CircularProgressIndicator(
                          color: kWhiteColor,
                        ),
                      );
                    }
                    if (snapshot.data == null) {
                      return const Text('start ',
                          style: TextStyle(
                            color: Colors.white,
                          ));
                    }

                    return AnimationLimiter(
                      key: UniqueKey(),
                      child: GridView.count(
                        crossAxisCount: columnCount,
                        children: snapshot.data!.docs.map(
                          (DocumentSnapshot document) {
                            Map<String, dynamic> data =
                                document.data()! as Map<String, dynamic>;
                            return AnimationConfiguration.staggeredGrid(
                              position: snapshot.data!.docs.length,
                              duration: const Duration(milliseconds: 375),
                              columnCount: columnCount,
                              child: ScaleAnimation(
                                child: FadeInAnimation(
                                  child: InkWell(
                                    onTap: () {},
                                    child: Container(
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        children: [
                                          Padding(
                                            padding: const EdgeInsets.all(8.0),
                                            child: Text(data['title'],
                                                style: const TextStyle(
                                                    color: Colors.white,
                                                    fontWeight: FontWeight.bold)),
                                          ),
                                          Padding(
                                            padding: const EdgeInsets.all(8.0),
                                            child: Text(data['discription'],
                                                style: const TextStyle(
                                                  color: Colors.white60,
                                                )),
                                          ),
                                        ],
                                      ),
                                      margin: EdgeInsets.only(
                                          bottom: _w / 30,
                                          left: _w / 60,
                                          right: _w / 60),
                                      decoration: const BoxDecoration(
                                        color: kLightBlackColor,
                                        borderRadius:
                                            BorderRadius.all(Radius.circular(20)),
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            );
                          },
                        ).toList(),
                      ),
                    );

A ScrollController was used after being disposed.

A ScrollController was used after being disposed.

When the exception was thrown, this was the stack: 
#0      ChangeNotifier._debugAssertNotDisposed.<anonymous closure> (package:flutter/src/foundation/change_notifier.dart:105:9)
#1      ChangeNotifier._debugAssertNotDisposed (package:flutter/src/foundation/change_notifier.dart:111:6)
#2      ChangeNotifier.addListener (package:flutter/src/foundation/change_notifier.dart:141:12)
#3      _FadingEdgeScrollViewState.initState (package:fading_edge_scrollview/src/fading_edge_scrollview.dart:128:17)

_controller.addListener(_onScroll); in the _FadingEdgeScrollViewState

This happens when I'm refreshing my list. Everything works great the first time. As soon as the rebuild happens it throws an error.

AnimationLimiter error when used with TabBar setState() called after dispose(): _AnimationLimiterState

I'm getting the following error

I/flutter ( 6014): ══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6014): The following assertion was thrown during a scheduler callback:
I/flutter ( 6014): setState() called after dispose(): _AnimationLimiterState#3e51d(lifecycle state: defunct, not
I/flutter ( 6014): mounted)
I/flutter ( 6014): This error happens if you call setState() on a State object for a widget that no longer appears in
I/flutter ( 6014): the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error
I/flutter ( 6014): can occur when code calls setState() from a timer or an animation callback.
I/flutter ( 6014): The preferred solution is to cancel the timer or stop listening to the animation in the dispose()
I/flutter ( 6014): callback. Another solution is to check the "mounted" property of this object before calling
I/flutter ( 6014): setState() to ensure the object is still in the tree.
I/flutter ( 6014): This error might indicate a memory leak if setState() is being called because another object is
I/flutter ( 6014): retaining a reference to this State object after it has been removed from the tree. To avoid memory
I/flutter ( 6014): leaks, consider breaking the reference to this object during dispose().
I/flutter ( 6014):
I/flutter ( 6014): When the exception was thrown, this was the stack:
I/flutter ( 6014): #0      State.setState.<anonymous closure> 
package:flutter/…/widgets/framework.dart:1208
I/flutter ( 6014): #1      State.setState 
package:flutter/…/widgets/framework.dart:1243
I/flutter ( 6014): #2      _AnimationLimiterState.initState.<anonymous closure> 
package:flutter_staggered_animations/src/animation_limiter.dart:45
I/flutter ( 6014): #3      SchedulerBinding._invokeFrameCallback 
package:flutter/…/scheduler/binding.dart:1117
I/flutter ( 6014): #4      SchedulerBinding.handleDrawFrame 
package:flutter/…/scheduler/binding.dart:1063
I/flutter ( 6014): #5      SchedulerBinding._handleDrawFrame 
package:flutter/…/scheduler/binding.dart:971
I/flutter ( 6014): #9      _invoke  (dart:ui/hooks.dart:251:10))
I/flutter ( 6014): #10     _drawFrame  (dart:ui/hooks.dart:209:3))
I/flutter ( 6014): (elided 3 frames from dart:async)

is it possibile to restart animation?

I have a screen (screen1) with ListView and 3 elements animated (working as expected).
When I click on an item, I load a new screen using Navigator (screen2).
When I go back from screen2 to screen1, there is obviously no animation again, but I would like to have a way to restart the animation.
Is this possible?

How to deal with Expanded ?

Hello,

Awesome code ;-)
Just a thing, I would like to animate a Column with Expanded widgets. But the ancestor is not anymore a Flex if I use your Widget.

> Expanded widgets must be placed directly inside Flex widgets.
> Expanded(no depth, flex: 1, dirty) has a Flex ancestor, but there are other widgets between them:
> - Opacity(opacity: 1.0)
> - Transform
> These widgets cannot come between a Expanded and its Flex.
> 

Any tips to work with ?

Thank you very much

Resize items of the list

I have tried to use your example in 2 ways:

  1. using the example of the ListView but on an horizontal-scroll list
  2. using the example of the GridView as it is

In both of the cases, I have tried in many ways to resize width and/or height of the elements of myChildList...however, in both cases it has not been possible, they keep showing taking the full height in the case of the ListView, and in some sort of pre-defined height and width for the GridView.

Can you help with that? how to achieve the desired width and height of the child items?

Animations not playing after Navigator.pop

On ScreenA I have some animations. When I pop out of ScreenB, back into ScreenA, the animations don't replay in spite of the screen rebuilding.

  1. I open ScreenA and the animations play.
  2. I click a button on ScreenA to go to SrceenB:
Navigator.of(context).push(MaterialPageRoute(builder: (context) => ScreenB()))
.then((value) {setState((){});});
  1. On ScreenB I click a button to return to ScreenA:
    Navigator.pop(context)
  2. setState gets called as expected and ScreenA is rebuilt, but the animations don't replay.

I'm testing on Android.
Note that this is how Flutter animations generally behave. The controller has to be manually restarted after Navigator.pop. My issue is that I don't have a way of restarting animations built using this package.

Is there any way of getting it to work the way I want it to work?

i get error sometimes

it works well, but i get some error sometimes

[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: 'package:flutter/src/animation/animation_controller.dart': Failed assertion: line 451 pos 7: '_ticker != null': AnimationController.forward() called after AnimationController.dispose()
AnimationController methods should not be used after calling dispose.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:40:39)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
#2      AnimationController.forward (package:flutter/src/animation/animation_controller.dart:451:7)
#3      _AnimationExecutorState.initState.<anonymous closure> (package:flutter_staggered_animations/src/animation_executor.dart:36:63)
#4      new Future.delayed.<anonymous closure> (dart:async/future.dart:316:39)
#5      _rootRun (dart:async/zone.dart:1120:38)
#6      _CustomZone.run (dart:async/zone.dart:1021:19)
#7      _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#8      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zon<…>

Add option for curve

This great, I have same concept with this package on my app but in my app I can set curve on my own. So it will be great if another dev can set his own curve. And this type of animation is great on tab, on my project i have function to trigger reverse animation when switch between tab, this also great if we can reverse the animation from this package.

Staggered List doesn't work when used with FutureBuilder

Here is my code:
`FutureBuilder<List>(
future: MenuService.getMenuCategory(),
initialData: [],
builder: (ctx, snapshot) {
return AnimationLimiter(
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.length,
physics: BouncingScrollPhysics(),
itemBuilder: (chipCtx, index) {
final isCatSelected = _selectedCategories
.contains(snapshot.data[index]);

                            return AnimationConfiguration.staggeredList(
                              position: index,
                              duration: Duration(seconds: 5),
                              child: FadeInAnimation(
                                child: Container(
                                  margin: const EdgeInsets.only(
                                      left: 5.0, right: 5.0),
                                  child: FilterChip(
                                    label: Text(
                                      snapshot.data[index],
                                      style: isCatSelected &&
                                              !_isAllCatSelected
                                          ? Theme.of(context)
                                              .textTheme
                                              .copyWith(
                                                caption: TextStyle(
                                                    color: Colors.white),
                                              )
                                              .caption
                                          : Theme.of(context)
                                              .textTheme
                                              .caption,
                                    ),
                                    backgroundColor:
                                        isCatSelected && !_isAllCatSelected
                                            ? Theme.of(context).primaryColor
                                            : Colors.transparent,
                                    shape: StadiumBorder(
                                      side: BorderSide(
                                        color:
                                            Theme.of(context).primaryColor,
                                        width: 1.5,
                                      ),
                                    ),
                                    onSelected: (isSelected) {
                                      if (isSelected) {
                                        if (isCatSelected) {
                                          setState(() {
                                            _isAllCatSelected = false;
                                            _selectedCategories.removeWhere(
                                                (category) =>
                                                    category ==
                                                    snapshot.data[index]);
                                          });
                                        } else {
                                          setState(() {
                                            _isAllCatSelected = false;
                                            _selectedCategories
                                                .add(snapshot.data[index]);
                                          });
                                        }
                                      }
                                    },
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      );
                    },
                  ),`

Here is my code used for staggered animation. This works absolutely fine if I removed FutureBuilder and used any hard coded list.

Flutter web, doesn't work well with GridView.builder

seeing this in the console:

════════ Exception caught by animation library ═════════════════════════════════
The provided ScrollController is currently attached to more than one ScrollPosition.
════════════════════════════════════════════════════════════════════════════════

Also scrolling doesn't update unless you scroll up a bunch to trigger it. And very slow.

Restarting animation on dropdown selection

Hi, im trying to combine the animation and the dropdown selection event. So when i select for the first time a value in the dropdown, it animates perfectly. But then when i change the value it doesnt animate anymore. Here is the source code

class _BackgroundSelectionPageState extends State<BackgroundSelectionPage> {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          height: double.infinity,
          width: double.infinity,
          color: Color(0xFF2E5266),
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          appBar: CustomAppBar(
            noDrawer: true,
            title: 'Background',
          ),
          body: Column(
            children: <Widget>[
              Stack(
                children: <Widget>[
                  Container(
                    height: 70,
                    //margin: const EdgeInsets.symmetric(horizontal: 5),
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black,
                          blurRadius:
                              10.0, // has the effect of softening the shadow
                          spreadRadius:
                              2.0, // has the effect of extending the shadow
                          offset: Offset(
                            0.0, // horizontal, move right 10
                            0.0, // vertical, move down 10
                          ),
                        )
                      ],
                      image: DecorationImage(
                          image: AssetImage(
                              Provider.of<NewCharacterDTO>(context)
                                  .characterRace
                                  .defaultBanner),
                          fit: BoxFit.fill),
                    ),
                  ),
                  Align(
                    alignment: Alignment.topRight,
                    child: Image.asset(
                      Provider.of<NewCharacterDTO>(context).characterClass.icon,
                      height: 70,
                    ),
                  )
                ],
              ),
              buildDropdown(context),
              Provider.of<NewCharacterDTO>(context).characterBackground != null
                  ? Expanded(
                      child: AnimationLimiter(
                        child: Column(
                          children: AnimationConfiguration.toStaggeredList(
                            duration: const Duration(milliseconds: 800),
                            childAnimationBuilder: (widget) => SlideAnimation(
                              horizontalOffset: 50.0,
                              child: FadeInAnimation(
                                child: widget,
                              ),
                            ),
                            children: 
                              Provider.of<NewCharacterDTO>(context).characterBackground.getDescriptionNewCharacter(MediaQuery.of(context).size.width, context)
                          ),
                        ),
                      ),
                    )
                  : Container()
            ],
          ),
        ),
      ],
    );
  }

  FutureBuilder buildDropdown(BuildContext context) {
    return FutureBuilder(
        future: HandbookRepository.getBackgrounds(context),
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Container(
                height: 100,
                width: 100,
                child: CircularProgressIndicator(),
              ),
            );
          }
          List<Background> backgrounds = snapshot.data;
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 10),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                DropdownButton(
                  items: backgrounds.map((Background value) {
                    return DropdownMenuItem(
                      value: value.index,
                      child: Text(
                        value.name,
                        style: TextStyle(
                            color: Color(0xFFCDC3B0),
                            fontSize: MediaQuery.of(context).size.width / 30,
                            fontFamily: 'Quicksand',
                            fontWeight: FontWeight.bold),
                      ),
                    );
                  }).toList(),
                  value: Provider.of<NewCharacterDTO>(context)
                              .characterBackground !=
                          null
                      ? Provider.of<NewCharacterDTO>(context)
                          .characterBackground
                          .index
                      : null,
                  onChanged: (value) {
                    //On selection we set the selected race and emtpy our newCharacter
                    Provider.of<NewCharacterDTO>(context).setBackground(
                        snapshot.data.singleWhere((x) => x.index == value));
                  },
                  //Hint
                  hint: Text(
                    'Select a Background',
                    style: TextStyle(
                        color: Color(0xFFCDC3B0),
                        fontSize: widget.width / 30,
                        fontFamily: 'Raleway',
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ],
            ),
          );
        });
  }
}

Non-fatal Exception: java.lang.Exception at _AnimationLimiterState.initState.<fn>(animation_limiter.dart:45)

Non-fatal Exception: java.lang.Exception: NoSuchMethodError: The method 'markNeedsBuild' was called on null.
Receiver: null
Tried calling: markNeedsBuild()
at State.setState(framework.dart:1168)
at _AnimationLimiterState.initState.(animation_limiter.dart:45)
at SchedulerBinding._invokeFrameCallback(binding.dart:1102)
at SchedulerBinding.handleDrawFrame(binding.dart:1049)
at SchedulerBinding._handleDrawFrame(binding.dart:957)

image

Only apply animation on entry

Currently when I use the FadeInAnimation on a Horizontal ListView, I will always get the fading when scrolling left to right. Even though the items where already added to the listview.

Can we stop the animation and only animate on first render/entry?

The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.

I use Android studio 4.1.0 and Flutter 2.0.1, flutter_staggered_animations 0.1.2.

/C:/Users/znvk3/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutter_staggered_animations-0.1.2/lib/src/animation_configuration.dart:161:20: Error: The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.

  • 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../sdk/flutter/packages/flutter/lib/src/widgets/framework.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
    return context.ancestorWidgetOfExactType(AnimationConfiguration)
    ^^^^^^^^^^^^^^^^^^^^^^^^^
    /C:/Users/znvk3/AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutter_staggered_animations-0.1.2/lib/src/animation_limiter.dart:75:20: Error: The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.
  • 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../sdk/flutter/packages/flutter/lib/src/widgets/framework.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
    return context.ancestorWidgetOfExactType(_AnimationLimiterProvider)
    ^^^^^^^^^^^^^^^^^^^^^^^^^

FAILURE: Build failed with an exception.

  • Where:
    Script 'D:\MK\project\sdk\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 991

  • What went wrong:
    Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'D:\MK\project\sdk\flutter\bin\flutter.bat'' finished with non-zero exit value 1

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 23s
Exception: Gradle task assembleDebug failed with exit code 1

How can I deal with BOTTOM OVERFLOWED error by used Column widget?

Widget body() => 
      SingleChildScrollView(
        padding: const EdgeInsets.all(15),
        child: AnimationLimiter(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: AnimationConfiguration.toStaggeredList(
              duration: const Duration(milliseconds: 375),
              childAnimationBuilder: (widget) => SlideAnimation(
                horizontalOffset: 50.0,
                child: FadeInAnimation(
                  child: widget,
                ),
              ),
              children: [
                Text('long long ........', style: TextStyle(color: AppColor.dark, fontSize: 14, fontWeight: FontWeight.normal),),
              ],
            ),
          ),
        ),
      );

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.