动画不会在页面开始处触发

Animation not firing at the start of the page in flutter

我想展示一个动画,每次我的容器都在页面的开头增加它的宽度和高度。 这里直接取initstate的值,不显示任何动画。

Padding(
              padding: const EdgeInsets.all(8.0),
              child: AnimatedContainer(
                duration: Duration(seconds: 2),
                curve: Curves.easeInOut,
                decoration: BoxDecoration(
                    image:DecorationImage(
                      fit: BoxFit.cover,
                      colorFilter: ColorFilter.mode(Colors.black54, BlendMode.darken),
                      image: AssetImage("lib/images/read.jpg"),
                    ),
                    borderRadius: BorderRadius.circular(10),
                    gradient: LinearGradient(
                        colors: <Color>[
                          Colors.yellowAccent,
                          Colors.blueAccent,
                        ]
                    )
                ),
                width: width,
                height: height,
                child: FlatButton(
                  onPressed: (){
                    Navigator.push(context, MaterialPageRoute(builder: (context)=>Quote_Categories())
                    );
                  },
                  child: Text(
                    'Reader',
                    style: TextStyle(
                      fontSize: 35,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
height=400;
width=250;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    registernotification();
    width=200;
    height=200;
  }

initState: Called when this object is inserted into the tree.

所以基本上你在读取值之前有 width:200height = 200,因为它们在 initState 中。您可以简单地用 Duration.zero 创建一个 Future method 并使用 setState 来更新 UI.

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

  changeContainerSize() {
    Future.delayed(Duration.zero).then((value) {
      setState(() {
        width = 200;
        height = 200;
      });
    });
  }

或使用addPostFrameCallback

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      setState(() {
        width = 200;
        height = 200;
      });
    });
  }