首页 > 解决方案 > Flutter 如何制作始终位于每一页顶部的底页

问题描述

底部表(不是底部栏)始终位于整个应用程序的顶部。如果打开页面,它始终位于顶部

WidgetsApp(
  debugShowCheckedModeBanner: false,
  color: Colors.pink,
  builder: (context, child) => Stack(
    children: [
      GetMaterialApp(
        debugShowCheckedModeBanner: false,
        color: Colors.pink,
        home: Scaffold(
          backgroundColor: Colors.amber,
          body: Center(
            child: TextButton(
              onPressed: () {},
              child: Text(
                'data',
              ),
            ),
          ),
        ),
      ),
       //bottomsheet
      Positioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: PlayerSheet(),
      )
    ],
  ),
);

像上面的东西

标签: flutterdart

解决方案


创建这样的东西作为你的页面包装器:

class StickyPageWrapper extends StatelessWidget {
  final Widget child;
  const StickyPageWrapper({Key key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;

    return Stack(
      fit: StackFit.expand,
      children: [
        child,
        Positioned(
          left: 0,
          bottom: 0,
          child: Hero(
            tag: 'bottom_sheet',
            child: Container(
              color: Colors.orange,
              height: size.height / 4,
              width: size.width,
            ),
          ),
        )
      ],
    );
  }
}

然后像这样在一页上使用它:

class Page1 extends StatelessWidget {
  const Page1({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StickyPageWrapper(
          child: Container(
        color: Colors.white38,
        child: Center(
            child: ElevatedButton(
          child: Text('Go to page 2'),
          onPressed: () {
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (context) => Page2()));
          },
        )),
      )),
    );
  }
}

然后对于另一个页面:

class Page2 extends StatelessWidget {
  const Page2({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StickyPageWrapper(
          child: Container(
        color: Colors.white38,
        child: Center(
            child: ElevatedButton(
          child: Text('Go back to page 1'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        )),
      )),
    );
  }
}

依此类推,所以你包装你的每一页。BottomSheet在页面之间导航时,我为您添加了一个英雄动画: https ://flutter.dev/docs/development/ui/animations/hero-animations ,使其看起来更漂亮更自然。

希望这会有所帮助,如果我能提供进一步的帮助,请告诉我。

注意:如果这是您的想法,这实际上不是一个BottomSheet小部件,因为通常该小部件是由ScaffoldState.showBottomSheet, 用于持久底部工作表或由showModalBottomSheet, 用于模态底部工作表隐式创建的。


推荐阅读