skip to Main Content

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


  1. I’d say you can pass the _currentIndex to a method that returns a FloatingActionButton with the callback that you want, something like this:

    FloatingActionButton? buildFloatingActionButton(
      int index,
      VoidCallback homeScreenCallback,
      VoidCallback profileScreenCallback,
      VoidCallback settingsScreenCallback,
    ) {
      if (index == 0) {
        return FloatingActionButton(
          onPressed: () => homeScreenCallback,
          child: const Icon(Icons.home),
        );
      } else if (index == 1) {
        return FloatingActionButton(
          onPressed: () => profileScreenCallback,
          child: const Icon(Icons.user),
        );
      } else if (index == 2) {
        return FloatingActionButton(
          onPressed: () => settingsScreenCallback,
          child: const Icon(Icons.settings),
        );
      }
    }
    

    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:

    floatingActionButton: buildFloatingActionButton(_selectedIndex),
    
    Login or Signup to reply.
  2. There are many ways:

    1. You can use State Management (preserve current index)
    2. simply pass _currentIndex to all the pages. (not that good)

    Simplest Way is Create a Floating Action Button in MyHomePage ‘s Scaffold

    Example:

    Scaffold(
          appBar: AppBar(
            title: Text('My App'),
          ),
          body: _screens[_currentIndex],
          floatingActionButton: FloatingActionButton(
                        onPressed: () {
                         switch (_currentIndex) {
                            case 0: // Page 1 Work
                              
                              break;
    
                             case 1: // Page 2 Work
                              
                              break;
    
                              case 2:
                                    // Page 3 Work
                              break;
    
                            default:
                            //Any Default Work
                          }
                        },
                      
                        child: Your UI //
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search