【发布时间】:2021-11-08 04:33:13
【问题描述】:
我使用late 关键字声明了两个变量,这样我就可以在initState 函数中初始化它们。
class _CustomNavBarState extends State<CustomNavBar>
with TickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _animation;
@override
void initState() {
super.initState();
AnimationController _animationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 500));
Animation<double> _animation =
Tween<double>(begin: 1, end: 0.8).animate(_animationController);
}
//...
如果 initState 在任何其他函数之前被调用,为什么会出现以下错误?
LateIinitializationError:字段“_animation@17200479”尚未初始化。
这里还有一些代码:
class CustomNavBar extends StatefulWidget {
const CustomNavBar(
{required this.icons,
required this.names,
required this.onPressed,
required this.activeIndex});
final List<IconData> icons;
final List<String> names;
final Function(int) onPressed;
final int activeIndex;
@override
_CustomNavBarState createState() => _CustomNavBarState();
}
class _CustomNavBarState extends State<CustomNavBar>
with TickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _animation;
@override
void didUpdateWidget(CustomNavBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.activeIndex != widget.activeIndex) {
_animate();
}
}
void _animate() {
_animationController.forward();
}
@override
void initState() {
super.initState();
AnimationController _animationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 500));
Animation<double> _animation =
Tween<double>(begin: 1, end: 0.8).animate(_animationController);
}
@override
Widget build(BuildContext context) {
return Container(
height: 90,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Theme.of(context).backgroundColor, Colors.black],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
)),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
for (var i = 0; i < widget.icons.length; i++)
TextButton(
style:
TextButton.styleFrom(splashFactory: NoSplash.splashFactory),
onPressed: () => widget.onPressed(i),
child: ScaleTransition(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
widget.icons[i],
size: 30,
color: i == widget.activeIndex
? Theme.of(context).accentColor
: Colors.white70,
),
Text(
widget.names[i],
style: TextStyle(
color: i == widget.activeIndex
? Theme.of(context).accentColor
: Colors.white70,
),
)
]),
scale: _animation))
],
),
);
}
}
【问题讨论】:
-
在 initState() 中移除 AnimationController 和 Animation
。您已经在上面定义了它们。 -
换句话说,您在初始化程序中编写这些变量的方式,实际上是在定义新的局部变量,这些变量会“隐藏”您尝试设置的实例变量。因此,实例变量保持未设置,导致您得到错误。 (我将这个问题标记为关闭,因为这是一个初学者的错误,基本上相当于一个错字,不太可能帮助未来的读者。)
标签: flutter dart dart-null-safety