Flutter: possible to detect when a drawer is open?

后端 未结 4 1682
Happy的楠姐
Happy的楠姐 2021-01-04 13:53

Is it possible to detect when a Drawer is open so that we can run some routine to update its content?

A typical use case I have would be to display the number of fol

4条回答
  •  走了就别回头了
    2021-01-04 14:47

    Detecting & Running Functions When Drawer Is Opened / Closed

    • Run initState() when open drawer by any action.
    • Run dispose() when close drawer by any action.
    class MyDrawer extends StatefulWidget {
        @override
        _MyDrawerState createState() => _MyDrawerState();
    }
    
    class _MyDrawerState extends State {
    
        @override
        void initState() {
            super.initState();
            print("open");
        }
    
        @override
        void dispose() {
            print("close");
            super.dispose();
        }
    
        @override
        Widget build(BuildContext context) {
            return Drawer(
                child: Column(
                    children: [
                        Text("test1"),
                        Text("test2"),
                        Text("test3"),
                    ],
                ),
            );
        }
    }
    

    State Management Considerations

    If you are altering state with these functions to rebuild drawer items, you may encounter the error: Unhandled Exception: setState() or markNeedsBuild() called during build.

    This can be handled by using the following two functions in initState() source

    Option 1

    WidgetsBinding.instance.addPostFrameCallback((_){
      // Add Your Code here.
    });
    

    Option 2

    SchedulerBinding.instance.addPostFrameCallback((_) {
      // add your code here.
    });
    

    Full Example of Option 1

    @override
    void initState() {
        super.initState();
        WidgetsBinding.instance.addPostFrameCallback((_) {
            // Your Code Here
        });
    }
    

提交回复
热议问题