Home > Net >  Unable to pass animationController as an argument to a stateful widget in flutter
Unable to pass animationController as an argument to a stateful widget in flutter

Time:11-29

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 .

CodePudding user response:

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.

CodePudding user response:

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()
  ];

CodePudding user response:

You can use late keyword for lazy initialization.

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

More about late keyword with declaration

  • Related