繁体   English   中英

Flutter 打开对话 animation

[英]Flutter open dialog with animation

我正在开发一个移动应用程序,我想通过一些很酷的对话框动画来改善用户体验,我不想只使用一个简单的弹出对话框。

基本上我想要的结果是这样的:

带动画的对话框

在网上搜索了一下,发现了类似的问题: Animation with hero and showDialog in flutter

我试图开发一些东西,结果如下:

我的对话框

我不知道如何重现容器中的东西。 也许在正确的 animation(第一张图片)中,他们放置了一个不可见的小对话框,一旦按下按钮,它就会与 animation 一起出现?

我应该在哪里输入框对话框的信息?

这是我使用的代码:

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;
                  });
                },
              ),
            ),
          ),
        ),
      ],
    ),

showDialogbuilder上使用ScaleTransition可以产生类似的效果。

builder将返回一个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"),
      ),
    );
  }

它会像这样使用

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

测试小部件:

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"),
      ),
    );
  }
}

我有一个解决方案:



    /**
     * @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),
        );
      }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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