1

I want to access a static variable in a stateful widget in a flutter. but it does not work. and someone said that is a private widget and I can't access it. so how can I access the variable isCollapsed in the below code:

class BottomNavBar extends StatefulWidget {
  final int activeTabIndex;

  const BottomNavBar({Key? key, required this.activeTabIndex})
      : super(key: key);

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

class _BottomNavBarState extends State<BottomNavBar> {
    static var isCollapsed = false;
 @override
  Widget build(BuildContext context) {
 Scaffold(
        body: SlidingUpPanel(
          controller: _pc,
          panelBuilder: (sc) {
            if (isCollapsed == false) _pc.hide();
            if (isCollapsed == true) _pc.show();
            return Container(
              child: Center(child: Text("Panel")),
            );
          },
          body: Text("something");
        ),  }
}

I want to change isCollapsed in another class, when clicked on the icon, isCollapsed changes to true.

class _PlayerPreviewState extends State<PlayerPreview> {
  @override
  Widget build(BuildContext context) {
    final String play = 'assets/icons/play.svg';
    var pageWidth = MediaQuery.of(context).size.width;
    return  Padding(
        padding: EdgeInsets.only(top: pageWidth * .04),
        child: IconButton(
        onPressed: () {
                               
         },
          icon: SvgPicture.asset(play),
                            ),
                          );}}

can anyone help me please how can I do it?

1 Answers1

1

Yes, _BottomNavBarState is private because it starts with underscore_. if you want to make it public, remove _ from name and it will be like


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

class BottomNavBarState extends State<BottomNavBar> {
  static var isCollapsed = false;
  

and use anywhere like BottomNavBarState.isCollapsed, but I should prefer state-management while the variable has effects on state.

For more about

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • can i use this? `BottomNavBarState.isCollapsed == true;` –  Oct 17 '21 at 12:59
  • thanks for sharing links.actually i dont know about state-management very well –  Oct 17 '21 at 13:05
  • i use this : `onPressed: () { BottomNavBarState.isCollapsed = true;},` but its nor working actually. –  Oct 17 '21 at 13:26
  • Because we aren't updating the state, and yes it just changes the value, that's why we need to handle the state, using `setState()` may help, consider learning about state-management like `setState` ,`provider`,`riverpod`,`bloc`+....... check that link you will get it. – Md. Yeasin Sheikh Oct 17 '21 at 13:39