Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

animate show or hide widgets with flutter

Tags:

flutter

i have something like this :

import 'package:flutter/material.dart';

class MyWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyWidgetState();
  }
}

class _MyWidgetState extends State<MyWidget> {
  bool loading = true;

  @override
  Widget build(BuildContext context) {
    if(loading) {
      return Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        child: Center(
          child: SizedBox(
            width: 24,
            height: 24,
            child: GestureDetector(
              onTap: _toggle,
              child: CircularProgressIndicator(),
            ),
          ),
        ),
      );
    } else {
      return Container(
        child: Center(
          child: GestureDetector(
            onTap: _toggle,
            child: Text("WELCOME"),
          ),
        ),
      );
    }
  }

  _toggle() {
    setState(() {
      loading = !loading;
    });
  }
}

my big problem with flutter is animating between toggling widgets

i want when _toggle called, loading widget fadeOut and after animation completed remove from screen and then show normal widget with fadeIn effect

how can i achieved to this ?

thanks

like image 348
DJafari Avatar asked Feb 09 '19 13:02

DJafari


People also ask

How do you check the visibility of a widget in Flutter?

Check if the widget is currently visible using bool isVisible() .

How do you fade widgets in Flutter?

There is no FadeIn/Out widgets in Flutter.


1 Answers

Correct way is using AnimatedSwitcher widget:

class MyWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyWidgetState();
  }
}

class _MyWidgetState extends State<MyWidget> {
  bool loading = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        child: loading ? Container(
          key: Key("loading"),
          color: Theme.of(context).scaffoldBackgroundColor,
          child: Center(
            child: SizedBox(
              width: 24,
              height: 24,
              child: GestureDetector(
                onTap: _toggle,
                child: const CircularProgressIndicator(),
              ),
            ),
          ),
        ) : Container(
          key: Key("normal"),
          child: Center(
            child: GestureDetector(
              onTap: _toggle,
              child: const Text("WELCOME"),
            ),
          ),
        ),
      ),
    );
  }

  _toggle() {
    setState(() {
      loading = !loading;
    });
  }
}

note: you must give a key for children, in my example if you remove key animation not work

like image 184
DJafari Avatar answered Sep 22 '22 23:09

DJafari