Usare AnimatedPositioned in Flutter

Mattepuffo's logo
Usare AnimatedPositioned in Flutter

Usare AnimatedPositioned in Flutter

AnimatedPositioned è un widget di Flutter che in pratica ci permette di animare un widget.

Quindi, all'interno di AnimatedPositioned metteremo un widget che verrà animato.

Nel nostro esempio, il widget si animerà al tap.

Ecco il codice di esempio:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Test',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool selected = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Stack(
        children: <Widget>[
          AnimatedPositioned(
            width: selected ? 200.0 : 50.0,
            height: selected ? 50.0 : 200.0,
            top: selected ? 50.0 : 150.0,
            duration: const Duration(seconds: 5),
            curve: Curves.fastOutSlowIn,
            child: GestureDetector(
              onTap: () => setState(() => selected = !selected),
              child: Container(
                color: Colors.amber,
                child: const Center(
                  child: Text("Tap me"),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

Enjoy!


Condividi

Commentami!