LateInitializationError: Field 'animationStatus' has not been initialized.

来源:7-6 动画Animation开发指南-AnimatedWidget与AnimatedBuilder-1【跟着做】

慕标5907691

2021-10-18

LateInitializationError: Field ‘animationStatus’ has not been initialized.
图片描述
执行下面的代码模拟器报上面的错误:

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';

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

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

class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController controller;
  late AnimationStatus animationState;
  late double animationValue;

  @override
  void initState() {
    super.initState();
    controller =
        AnimationController(duration: const Duration(seconds: 2), vsync: this);
    // #docregion addListener
    animation = Tween<double>(begin: 0, end: 300).animate(controller)
      ..addListener(() {
        // #enddocregion addListener
        setState(() {
          animationValue = animation.value;
        });
        // #docregion addListener
      })
      ..addStatusListener((AnimationStatus state) {
        setState(() {
          print(state);
          animationState = state;
        });
      });
    // #enddocregion addListener
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 50),
      child: Column(
        children: <Widget>[
          GestureDetector(
            onTap: () {
              controller.reset();
              controller.forward();
            },
            child: Text('Start', textDirection: TextDirection.ltr),
          ),
          Text('State:' + animationState.toString(),
              textDirection: TextDirection.ltr),
          Text('Value:' + animationValue.toString(),
              textDirection: TextDirection.ltr),
          Container(
            height: animation.value,
            width: animation.value,
            child: FlutterLogo(),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
写回答

1回答

CrazyCodeBoy

2021-10-19

如截图报错, late AnimationStatus animationState没有在init方法中初始化导致的

0
1
qq_麻烦_uwxM46
Text('State:' + animationState.toString() 是这里使用 animationState 报错, 所以上面要写成可空: AnimationStatus? animationStatus; double? animationValue;
2022-09-18
共1条回复

Flutter从入门到进阶 实战携程网App 一网打尽核心技术

解锁Flutter开发新姿势,,系统掌握Flutter开发核心技术。

4788 学习 · 3270 问题

查看课程