stackunderflow
stackunderflow

Reputation: 1774

Flutter - AppBar as a StatefulWidget with collapsible bottom

I want to create an AppBar as a StatefulWidget with a collapsible bottom widget. But I can't change the value of preferredSize on bottom toggle with setState. If I set the preferredSize fixed to kToolbarHeight, the top bar will be pushed upward. If I double it, collapsing the bottom will leave an empty space. This problem does not happens if I don't create the AppBar as a StatefulWidget because I can always update the state.

class MyAppBar extends StatefulWidget implements PreferredSizeWidget{
    
  View({Key? key}) : super(key : key);

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight * 2);

  @override
  State<MyAppBar> createState() => MyAppBarState();
}

class MyAppBarState extends State<MyAppBar>{

  bool expand = false;

  @override
  Widget build(BuildContext context){
    ...
    return AppBar(
      ...
      bottom : expand ? PreferredSize(
        ...
      ) : null,
    );
  }
}

Upvotes: 1

Views: 419

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63559

You can test this widget,

class TSA extends StatelessWidget implements PreferredSizeWidget {
  const TSA({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final ValueNotifier<bool> _isExpanded = ValueNotifier(true);

    return ValueListenableBuilder<bool>(
      valueListenable: _isExpanded,
      builder: (context, value, child) {
        return AppBar(
          title: ElevatedButton(
            child: Text("update ${_isExpanded.value}"),
            onPressed: () {
              _isExpanded.value = !_isExpanded.value;
            },
          ),
          bottom: value
              ? const PreferredSize(
                  child: Text("bottom"), preferredSize: Size.fromHeight(43))
              : null,
        );
      },
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(kToolbarHeight * 2);
}

Upvotes: 1

Related Questions