首页 > 解决方案 > 尝试为 ElevatedButton 设置动画时出现此错误

问题描述

我目前正在尝试为提升的按钮设置动画,只是想为提升的属性设置动画。所以我在 VS 代码中搭建了一个新的颤振启动器应用程序,并在动画和动画控制器的相关代码中添加了,但是我不断收到这个错误:类型'double'不是类型'MaterialStateProperty<double?>的子类型? ' 我不明白为什么,这是我的代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {

  AnimationController animationController;
  Animation animation;

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

      animationController = AnimationController(
        vsync: this,
        duration: Duration(seconds: 5),
      );

      animation = Tween(begin: 50.0, end: 150.0).animate(
        CurvedAnimation(
          parent: animationController, 
          curve: Interval(0.0, 1.0, curve: Curves.easeInOut),
        ),
      );
  }

  @override void dispose() {
      animationController.dispose();

      super.dispose();
    }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: (){
                animationController.forward();
              }, 
              child: Text("Button Text"),
              style: ButtonStyle(
                elevation: animation.value,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){},
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

标签: flutterdartflutter-animation

解决方案


根据ButtonStyle文档:

许多 ButtonStyle 属性是MaterialStateProperty对象,它们根据按钮的状态解析为不同的值。例如,颜色属性是使用 MaterialStateProperty 定义的,并且可以根据按钮是否被按下、悬停、聚焦、禁用等解析为不同的颜色。

因此,您需要做的是将animation value作为 MaterialStateProperty 传递。

在您的情况下,它看起来像这样:

style: ButtonStyle(  
  elevation: MaterialStateProperty.all(animation.value), 
),

查看MaterialStatePropertyClass 文档以获取更多信息。


推荐阅读