Home > database >  Creating a global floating button in flutter
Creating a global floating button in flutter

Time:01-27

Is it possible to have floating button visible throughout the life cycle of the app on top of all pages? I know that with Scaffold I can have it but it only works for that page and i'll lose it once I push a new page on the navigator stack.

CodePudding user response:

Yes, OverlayEntry is made for this purpose.

For example:

ElevatedButton(
  child: Text("Overlay Test"),
  onPressed: () {
    final entry = OverlayEntry(
      builder: (context) => Container(
        color: Colors.blue,
      ),
    );
    Overlay.of(context)?.insert(entry);
  },
)

If you want to remove it later, you can save the entry variable and then call entry.remove() when needed.

CodePudding user response:

One option is to use the builder of the MaterialApp to create a Stack with your Button on top:

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test',
      home: TestPage(),
      initialRoute: "/test",
      builder: (context, child) {
        return Scaffold(
          body: Stack(
            children: [
              child!,
              Positioned(
                    left: 0,
                    bottom: 0,
                    child: **your button here**,
              ),
            ],
          ),
        );
      },
      routes: routes(context),
    );
  }
}
  •  Tags:  
  • Related