Flutter Tricks
Published on

How to Change Floating Action Button Position in Flutter

The Floating Action Button (FAB) is a popular UI element in Flutter that allows users to perform a primary action within the app. By default, the FAB is positioned at the bottom right corner of the screen. However, there are times when you may need to change its position to better suit your app's design or functionality.

In this article, we will explore how to change the position of the Floating Action Button in Flutter using prebuilt locations.

Using Prebuilt Locations

Flutter provides several prebuilt locations for the Floating Action Button, making it easy to position it without much code. These prebuilt locations are available through the FloatingActionButtonLocation class.

To use a prebuilt location, follow these steps:

  1. Create an instance of the desired prebuilt location, such as FloatingActionButtonLocation.centerFloat.
  2. Assign the prebuilt location to the floatingActionButtonLocation property of the Scaffold widget.

Here's an example of changing the FAB position to the center using the centerFloat prebuilt location:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('FAB Positioning'),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          child: Icon(Icons.add),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      ),
    );
  }
}

By specifying FloatingActionButtonLocation.centerFloat as the value for floatingActionButtonLocation, the FAB will now appear at the center of the screen horizontally, while still floating above the rest of the content.

You can use other prebuilt locations such as endFloat, endTop, centerDocked, etc., to position the FAB according to your app's requirements.

Summary

In this article, we learned how to change the position of the Floating Action Button (FAB) in Flutter using prebuilt locations. Flutter provides several prebuilt locations such as centerFloat, endFloat, endTop, centerDocked, etc., which allows you to easily position the FAB at different locations on the screen.

By using the floatingActionButtonLocation property of the Scaffold widget and assigning a prebuilt location, you can customize the position of the FAB to better suit your app's design and functionality.

Experiment with different prebuilt locations to find the best position for your Floating Action Button in your Flutter app!