簡體   English   中英

如何在 Flutter 中制作一個浮動的 AppBar?

[英]How to make a floating AppBar in Flutter?

在此處輸入圖片說明

我想在 Flutter 中創建一個浮動的 AppBar,它覆蓋在我的 UI 上並在用戶向上滾動時關閉。 我曾嘗試使用此依賴項 - https://pub.dev/packages/material_floating_search_bar但這僅用於搜索某些內容。

更新:這是我的代碼 -

DefaultTabController(
      length: 2,
      child: Scaffold(
          body: Stack(
        children: [
          Positioned(
            top: 15,
            left: 15,
            right: 15,
            child: SafeArea(
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: AppBar(
                  title: Text('Hello', style: kTasksStyle),
                  centerTitle: true,
                  backgroundColor: kGreen,
                ),
              ),
            ),
          ),
        ],
      )),
    );

如何在AppBar的底部參數中添加TabBar

您可以使用Stack ,將您的內容和 App bar 作為子項。 要在滾動時關閉,您可以根據 ScrollController 的偏移量隱藏應用欄或使用動畫。

截屏:

在此處輸入圖片說明


為簡單起見,我使用了ListView

代碼:

class _MainPageState extends State<HomePage> {
  final double _appBarHeight = 56;
  final double _topPadding = 20;
  ScrollController _controller;
  double _opacity = 1;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _controller.addListener(_listener);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _listener() {
    final offset = _controller.offset;
    if (offset > _appBarHeight) {
      if (_opacity != 0) {
        setState(() {
          _opacity = 0;
          if (_opacity < 0) _opacity = 0;
        });
      }
    } else {
      setState(() {
        _opacity = 1 - (offset / _appBarHeight);
        if (_opacity > 1) _opacity = 1;
      });
    }
  }

  Widget get _mainContent {
    return ListView.builder(
      controller: _controller,
      padding: EdgeInsets.only(top: _topPadding + _appBarHeight),
      itemCount: 20,
      itemBuilder: (_, i) => ListTile(title: Text('Item $i')),
    );
  }

  Widget get _appBar {
    return Opacity(
      opacity: _opacity,
      child: SizedBox.fromSize(
        size: Size.fromHeight(_appBarHeight),
        child: AppBar(
          title: Text('AppBar'),
          centerTitle: false,
          backgroundColor: Colors.grey,
          leading: Icon(Icons.menu),
          actions: [
            IconButton(
              icon: Icon(Icons.place),
              onPressed: () {},
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          _mainContent,
          Positioned(
            top: _topPadding,
            left: 0,
            right: 0,
            child: _appBar,
          ),
        ],
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM