0

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 .

Biswas Sampad
  • 413
  • 1
  • 6
  • 19

3 Answers3

0

Add this getter to your State class:

AnimationController get controller => _controller;

Then in your widgetList list, replace _controller with controller :

    List<Widget> widgetList = [
    DashboardView(),
    CallLogs(
      animationController: controller,
    ),
    ContactLogs(),
    UserProfile()
  ];
Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
0

replace List<Widget> widgetList = with List<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.

Rahul
  • 3,529
  • 1
  • 5
  • 19
0

You can use late keyword for lazy initialization.

 late List<Widget> widgetList = [
    DashboardView(),
    CallLogs(
      animationController: _controller,
    ),
    ContactLogs(),
    UserProfile()
  ];

More about late keyword with declaration

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56