Animated Switcher and Bloc Builder
Asked Answered
P

1

7

im new to bloc pattern in flutter.

One of my states classes have a list of widget and an index as a field. My goal is to update the child of an Animated Switcher using this state's widgets.

return AnimatedSwitcher(
  duration: Duration(milliseconds: 500),
  child: BlocBuilder<WelcomeBloc, WelcomeBlocState>(
    builder: (context, state) {

      if(state is MyState)
        return state.widgetList[state.index];

      else return Container();

    },
  ),
);

I have also tried the other way around, returning the animated switcher in the bloc builder and the result is the same

When yield is called, the widget is changed but without any animation.

What am I missing?

Pahang answered 7/11, 2019 at 13:25 Comment(0)
J
17

A child widget of AnimatedSwitcher has to change:

return BlocBuilder<WelcomeBloc, WelcomeBlocState>(
  builder: (context, state) {
    return AnimatedSwitcher(
      duration: Duration(milliseconds: 500),
      child: state is MyState ? state.widgetList[state.index] : Container(key: Key('key2')),
    );
  },
);

And don't forget to set different keys for child widgets.

Jasisa answered 7/11, 2019 at 13:34 Comment(1)
When the builder function of BlocBuilder is called, won't the complete AnimatedSwitcher be rebuilt and not just its child? How is it different from creating multiple AnimatedSwitcher widgets for each child widget (for each state)?Fisticuffs

© 2022 - 2024 — McMap. All rights reserved.