I have a Flutter app with a BottomNavigationBar
that allows users to navigate between different screens (HomeScreen
, ProfileScreen
, and SettingsScreen
). I want to implement a FloatingActionButton
in the MyHomePage
widget that performs different actions based on which screen is currently displayed. The different actions themselves are defined in the corresponding pages as functions (HomeScreen
, ProfileScreen
, SettingsScreen
).
For instance:
- On the
HomeScreen
, the FAB might open a new post dialog. - On the
ProfileScreen
, it might navigate to the edit profile page. - On the
SettingsScreen
, it might open the app’s settings.
How can I make the FAB’s onPressed function aware of the current screen and execute the specific logic associated with that screen?
Here’s a simplified version of my code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
final List<Widget> _screens = [
HomeScreen(),
ProfileScreen(),
SettingsScreen(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: _screens[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: 'Settings',
),
],
),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Home Screen'),
);
}
}
class ProfileScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Profile Screen'),
);
}
}
class SettingsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Settings Screen'),
);
}
}
Any help or guidance would be much appreciated!
2
Answers
I’d say you can pass the _currentIndex to a method that returns a FloatingActionButton with the callback that you want, something like this:
I’m not sure if the typing is correct, but this idea should work since your widget is Stateful so it will update the FAB once the index changes.
You can then call this function in your Scaffold:
There are many ways:
Simplest Way is Create a Floating Action Button in MyHomePage ‘s Scaffold
Example: