【问题标题】:How can I show a floating button over all pages in Flutter?如何在 Flutter 的所有页面上显示浮动按钮?
【发布时间】:2021-08-24 15:58:11
【问题描述】:

我想在 Flutter 中继续显示浮动按钮或小部件,即使页面被 Navigator.of(context).push() 更改,就像放在底部的迷你音乐播放器一样。

我该如何实现??

【问题讨论】:

标签: flutter


【解决方案1】:

您可以将脚手架提取为包含底部工作表的布局,并在您构建的每个页面中使用此布局,并传入标题、正文等,以便底部工作表在所有页面中保持不变。片段如下。

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Persistent Bottom Sheet',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        brightness: Brightness.dark,
      ),
      initialRoute: "/",
      routes: {
        "/": (context) => Home(),
        "/library": (context) => Library(),
      },
    );
  }
}

class Home extends StatelessWidget {
  Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Layout(
      title: "Home",
      body: Center(
        child: Text("Home"),
      ),
      actions: <Widget>[
        InkWell(
          onTap: () {
            Navigator.of(context).pushNamed("/library");
          },
          child: Tooltip(
            message: "Go To Library",
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Icon(Icons.library_music),
            ),
          ),
        )
      ],
    );
  }
}

class Library extends StatelessWidget {
  Library({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Layout(
      title: "Library",
      body: Center(
        child: Text("Library"),
      ),
    );
  }
}

class Layout extends StatelessWidget {
  final String title;
  final Widget body;
  final List<Widget>? actions;

  const Layout({
    Key? key,
    required this.title,
    required this.body,
    this.actions,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(title),
        actions: actions,
      ),
      body: body,
      bottomSheet: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(15),
        color: Theme.of(context).cardColor,
        child: Text("Persistent Bottom Sheet"),
      ),
    );
  }
}

【讨论】:

  • 谢谢,但是当页面更改时,底部工作表会显示刷新动画,因为工作表链接到每个页面。有什么办法让它浮动并稳定吗?
  • 默认页面转换发生是因为我们使用的是 MaterialPageRoute。如果您不想要过渡动画,可以使用 PageRouteBuilder。检查此答案以获取更多详细信息:stackoverflow.com/a/57774013/16045128
猜你喜欢
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多