简体   繁体   中英

Flutter open dialog with animation

I'm developing a mobile application and I want to improve the user experience with some cool animations for a dialog box and I don't want just to use a simple pop-up dialog.

Basically the result that I want I something like that:

带动画的对话框

I searched online and I found a similar problem: Animation with hero and showDialog in flutter .

I tried to develop somethings and this is the results:

我的对话框

I'm not getting how to reproduce the things in the container. Maybe in the correct animation (first image) they putted an invisible small dialog box that once the button is pressed it appears with the animation?

Where should I enter the information for the box dialog?

This is the code that I used:

Stack(
      children: [
        Positioned(
          child: GoogleMap(
            initialCameraPosition: CameraPosition(
              target: LatLng(10, 10),
            ),
          ),
        ),
        Positioned(
          child: Container(
            height: 100,
            width: w,
            color: Colors.white,
          ),
        ),
        Positioned(
          child: Padding(
            padding: const EdgeInsets.only(top: 50),
            child: Align(
              alignment: Alignment.topCenter,
              child: GestureDetector(
                child: AnimatedContainer(
                  height: _h,
                  width: _w,
                  color: Colors.lightGreen,
                  duration: Duration(seconds: 1),
                  child: Center(
                    child: Text(
                      'Title',
                    ),
                  ),
                ),
                onTap: () {
                  setState(() {
                    _h = 200;
                    _w = w * 0.9;
                  });
                },
              ),
            ),
          ),
        ),
      ],
    ),

I would suggest you use the Container transform transition pattern from the official animations package https://pub.dev/packages/animations

Preview: https://github.com/flutter/packages/raw/master/packages/animations/example/demo_gifs/container_transform_lineup.gif

Using ScaleTransition on showDialog 's builder can have similar effect.

The builder will return a StatefulWidget

 @override
  Widget build(BuildContext context) {
    return ScaleTransition(
      scale: animation,
      alignment: Alignment.topLeft, // use different alignment
      child: const AlertDialog(
        backgroundColor: Colors.cyanAccent,
        title: Text("title"),
      ),
    );
  }

And it will be used like

showDialog(
  context: context,
  builder: (context) => CustomAlertDialog(),
);

Test Widget:

class CustomAlertDialog extends StatefulWidget {
  const CustomAlertDialog({Key? key}) : super(key: key);

  @override
  _CustomAlertDialogState createState() => _CustomAlertDialogState();
}

class _CustomAlertDialogState extends State<CustomAlertDialog>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> animation;

  @override
  void initState() {
    super.initState();
    _initScaleAnimation();
  }

  _initScaleAnimation() {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..addListener(() => setState(() {}));

    animation = Tween<double>(begin: 0, end: 1.0).animate(controller);

    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return ScaleTransition(
      scale: animation,
      alignment: Alignment.topLeft, // use different alignment
      child: const AlertDialog(
        backgroundColor: Colors.cyanAccent,
        title: Text("title"),
      ),
    );
  }
}

I have a solution:



    /**
     * @author Gilmar N. Lima
     * @email gstrtoint@gmail.com or adminti@isofttec.com.br
     * @create date 25-01-2023  12:25:20
     * @modify date 25-01-2023  12:25:20
     * @desc [description]
     */
    
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(const MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            // This is the theme of your application.
            //
            // Try running your application with "flutter run". You'll see the
            // application has a blue toolbar. Then, without quitting the app, try
            // changing the primarySwatch below to Colors.green and then invoke
            // "hot reload" (press "r" in the console where you ran "flutter run",
            // or simply save your changes to "hot reload" in a Flutter IDE).
            // Notice that the counter didn't reset back to zero; the application
            // is not restarted.
            primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      const MyHomePage({super.key, required this.title});
    
      // This widget is the home page of your application. It is stateful, meaning
      // that it has a State object (defined below) that contains fields that affect
      // how it looks.
    
      // This class is the configuration for the state. It holds the values (in this
      // case the title) provided by the parent (in this case the App widget) and
      // used by the build method of the State. Fields in a Widget subclass are
      // always marked "final".
    
      final String title;
    
      @override
      State createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State {
      int _counter = 0;
    
      GlobalKey _widgetKey = GlobalKey();
    
      void _incrementCounter() {
        setState(() {
          // This call to setState tells the Flutter framework that something has
          // changed in this State, which causes it to rerun the build method below
          // so that the display can reflect the updated values. If we changed
          // _counter without calling setState(), then the build method would not be
          // called again, and so nothing would appear to happen.
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        // This method is rerun every time setState is called, for instance as done
        // by the _incrementCounter method above.
        //
        // The Flutter framework has been optimized to make rerunning build methods
        // fast, so that you can just rebuild anything that needs updating rather
        // than having to individually change instances of widgets.
        return Scaffold(
          appBar: AppBar(
            // Here we take the value from the MyHomePage object that was created by
            // the App.build method, and use it to set our appbar title.
            title: Text(widget.title),
          ),
          body: Center(
            // Center is a layout widget. It takes a single child and positions it
            // in the middle of the parent.
            child: Column(
                // Column is also a layout widget. It takes a list of children and
                // arranges them vertically. By default, it sizes itself to fit its
                // children horizontally, and tries to be as tall as its parent.
                //
                // Invoke "debug painting" (press "p" in the console, choose the
                // "Toggle Debug Paint" action from the Flutter Inspector in Android
                // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
                // to see the wireframe for each widget.
                //
                // Column has various properties to control how it sizes itself and
                // how it positions its children. Here we use mainAxisAlignment to
                // center the children vertically; the main axis here is the vertical
                // axis because Columns are vertical (the cross axis would be
                // horizontal).
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: ElevatedButton(
                      key: _widgetKey,
                      child: const Text('Alert'),
                      onPressed: () {
                        _scaleDialog();
                      },
                    ),
                  )
                ]),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: const Icon(Icons.add),
          ), // This trailing comma makes auto-formatting nicer for build methods.
        );
      }
    
      Widget _dialog(BuildContext context) {
        return AlertDialog(
          title: const Text("Dialog title"),
          content: const Text("Simple Dialog content"),
          actions: [
            TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: const Text("Ok"))
          ],
        );
      }
    
      void _scaleDialog() {
        showGeneralDialog(
          context: context,
          pageBuilder: (ctx, a1, a2) {
            return Container();
          },
          transitionBuilder: (ctx, a1, a2, child) {
            var curve = Curves.easeInOut.transform(a1.value);
            RenderBox? boxs =
                _widgetKey.currentContext!.findRenderObject() as RenderBox?;
            Offset posit = boxs!.localToGlobal(Offset.zero);
    
            return Transform.scale(
                scale: curve,
                child: _dialog(ctx),
                origin: posit,
                alignment: AlignmentGeometry.lerp(null, null, 2));
          },
          transitionDuration: const Duration(milliseconds: 900),
        );
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM