Implicit Flutter Animations

Oct 4 2022 Dart 2.17, Flutter 3.0, Visual Studio Code 1.7

Part 2: Implicit Animations in Action

10. Animate the Item Switcher's Selector

Episode complete

Play next episode

Next
Save for later
About this episode
See versions
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 9. Animate an Item Switcher Next episode: 11. Know When to Use Implicit Animations

The student materials have been reviewed and are updated as of August 2022.

The updated material uses null safety and also deploys the use coding practises encouraged by the Flutter as per the Flutter lint rules and a few addons of practises that are considered good here at raywenderlich (see analysis_options.yaml in the material for more info).

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

The next and stage in our animation sequence is to animate the position of the bottom selector widget. We want to animate horizontal position to the center of the selected item.

...
GlobalKey _itemKey1 = GlobalKey();
GlobalKey _itemKey2 = GlobalKey();
GlobalKey _itemKey3 = GlobalKey();
...
void _selectIem(int id){
    ...
    late GlobalKey globalKey;
    switch (id) {
        case 1:
            globalKey = _itemKey1;
            break;
        case 2:
            globalKey = _itemKey2;
            break;
        case 3:
            globalKey = _itemKey3;
            break;
        default:
    }
    ...
}

// Insdide Row of build method
InkWell(
    key: _itemKey1,
    ...
InkWell(
    key: _itemKey2,
    ...
InkWell(
    key: _itemKey3,
    ...
double _selectorPositionX = 24;
final double _selectorWidth = 30;
...
void _selectItem(int id) {
    ...
    // Remove the setState() called here
    _setWidgetPositionX(selectedGlobalKey);
}
...
// Paste this
_setWidgetPositionX(GlobalKey key) {
    final widgetRenderBox =
        key.currentContext?.findRenderObject() as RenderBox?;

    if (widgetRenderBox != null) {
      final widgetPosition = widgetRenderBox.localToGlobal(Offset.zero);
      final widgetSize = widgetRenderBox.size;

      _selectorPositionX =
          widgetPosition.dx - ((_selectorWidth - widgetSize.width) / 2);
    }
    setState(() {});
}
...
// Inside the build method
AnimatedPositioned(
    duration: const Duration(milliseconds: 450),
    curve: Curves.fastOutSlowIn,
    left: _selectorPositionX,
    ...
    child: Container(
        ...
        width: _selectorWidth,
...
@override
void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
        _setWidgetPositionX(_itemKey1);
    });
}