How to animate widget generated by StreamBuilder?

3,797

Solution 1

Your BlocBuilder should wrap the AnimatedSwitcher and not the opposite.

The animation of AnimatedSwitcher happens when its direct child change. But in your case, the direct child is always BlocBuilder.

StreamBuilder(
  stream: stream,
  builder: (context, snapshot) {
    return AnimatedSwitcher(
      duration: const Duration(seconds: 4),
      child: snapshot.hasData
        ? Text(snapshot.data)
        : CircularProgressIndicator();
    );
  }
),

Solution 2

You could try with AnimatedCrossFade It accepts 2 children, duration and state (AnimatedCrossFadeState.showFirst and AnimatedCrossFadeState.showSecond) and it will animate fade between two children.

documentation: https://docs.flutter.io/flutter/widgets/AnimatedCrossFade-class.html

Share:
3,797
EvilMonkeyPL
Author by

EvilMonkeyPL

Updated on December 10, 2022

Comments

  • EvilMonkeyPL
    EvilMonkeyPL over 1 year

    I'm trying to generate content of my screen by using StreamBuilder. It's working pretty well along bloc pattern, but there is one thing that I'm struggling with. How to animate changes between generated content (WidgetA and WidgetB) like fade or slide effect?

        ...
        return AnimatedSwitcher(
          duration: Duration(seconds: 4),
          child: BlocBuilder<ContentEvent, int>(
            bloc: bloc,
            builder: (context, contentID) {
              if (contentID == 1) {
                return WidgetA();
              } else {
                return WidgetB();
              }
            },
          ),
        );
        ...
    
  • Michał Jabłoński
    Michał Jabłoński over 4 years
    Thanks! I've been looking for this quite long
  • nmw
    nmw over 4 years
    Note that if the types are the same (say if you wrap the switcher's widgets in Container or Centre) then the animation won't happen unless you give them different keys. See api.flutter.dev/flutter/widgets/AnimatedSwitcher-class.html