首页 > 解决方案 > 对话框的动画背景颜色

问题描述

我创建了一个颜色补间动画来改变对话框的背景颜色,但它仍然没有改变。

我的代码:

void _showDialog() {
AnimationController? animationController = AnimationController(
    vsync: this,
    duration: const Duration(
      milliseconds: 1000,
    )
);
Animation<Color?>? animation = ColorTween(
  begin: Colors.black54,
  end: Colors.redAccent,
).animate(animationController!.view);


showDialog(
    context: context,
    builder: (BuildContext context) {
      return Dialog(
        backgroundColor: animation!.value,
        elevation: 6,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8)
        ),
        child: MyTextWidget(
          onSubmitted: (text) {
            animationController.forward();
          }
      );
    }
).then((value) => {
  print(value)
});
}

然后我使用animationController.forward(),但没有任何反应。

我究竟做错了什么?

标签: flutterdartdialog

解决方案


There was no animation because you did not wrap your dialog with any widget that would animate. Please see the working code below the only thing I did was to wrap Dialog with a AnimatedBuider and call animationController.repeat(). You may call animationController.forward from your custom text widget :

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidgets(),
        ),
      ),
    );
  }
}

class MyWidgets extends StatefulWidget {
  @override
  _MyWidgetsState createState() => _MyWidgetsState();
}

class _MyWidgetsState extends State<MyWidgets> with TickerProviderStateMixin {
  void _showDialog() {
    AnimationController animationController = AnimationController(
        vsync: this,
        duration: const Duration(
          milliseconds: 1000,
        ));
    Animation<Color> animation = ColorTween(
      begin: Colors.black54,
      end: Colors.redAccent,
    ).animate(animationController.view);

    showDialog(
        context: context,
        builder: (BuildContext context) {
          animationController.repeat();
          return AnimatedBuilder(
              animation: animation,
              builder: (context, snapshot) {
                return Dialog(
                    backgroundColor: animation.value,
                    elevation: 6,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8)),
                    child: Container());
              });
        }).then((value) => {print(value)});
  }

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      onPressed: () {
        _showDialog();
        //animationController
      },
      child: const Text("Show Dialog"),
    );
  }
}

推荐阅读