I am trying to pass the animationController as an argument to my statefullwidget . But getting this error .
The instance member ‘_controller’ can’t be accessed in an initializer.
Try replacing the reference to the instance member with a different
expression
I am just trying to add animation to a nav change via bottom navigator .
my parent widget looks like this .
class _DashboardState extends State<Dashboard>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
_controller = AnimationController(
vsync: this, duration: const Duration(milliseconds: 150));
_controller.forward();
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
List<Widget> widgetList = [
DashboardView(),
CallLogs(
animationController: _controller,
),
ContactLogs(),
UserProfile()
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: widgetList[context.watch<NavigationIndex>().index],
),
bottomNavigationBar: const BottomNavigator(),
);
}
}
and child looks like this
import 'package:flutter/material.dart';
class CallLogs extends StatefulWidget {
final AnimationController animationController;
const CallLogs({super.key, required this.animationController});
@override
State<CallLogs> createState() => _CallLogsState();
}
class _CallLogsState extends State<CallLogs> {
@override
Widget build(BuildContext context) {
return Container(
child: const Text("Call logs"),
);
}
}
Any help will be appreciated . Thanks in advance . Cheers .
3
Answers
Add this
getter
to yourState
class:Then in your
widgetList
list, replace_controller
withcontroller
:replace
List<Widget> widgetList =
withList<Widget> get widgetList =>
The widgetList variable is assigned when the class object is created. By that time, _controller is not initialized hence it’s null.
You can use
late
keyword for lazy initialization.More about late keyword with declaration