Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom offset to "FloatingActionButtonLocation" in the scaffold, in flutter?

Tags:

flutter

So recently FloatingActionButtonLocation was introduced and it has four values all for bottom alignment. I want it at the top, halfway below the app bar. But I couldn't figure out how to set a custom offset. The official documentation is also scarce on this.

like image 365
AgentTango Avatar asked Sep 16 '25 17:09

AgentTango


1 Answers

This is against material design guidelines.But you can do this by changing scaffoldGeometry.contentBottom to scaffoldGeometry.contentTop from original source code.Below code should work

import 'package:flutter/material.dart';
import 'dart:math' as math;


class HomeHeader extends StatefulWidget {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  @override
  HomeHeaderState createState() {
    return new HomeHeaderState();
  }
}

class HomeHeaderState extends State<HomeHeader> {

  static const FloatingActionButtonLocation centerDocked = _CenterDockedFloatingActionButtonLocation();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: widget._scaffoldKey,
      appBar: AppBar(
        title: Text('duh'),
      ),
      floatingActionButtonLocation:centerDocked,
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add), onPressed: () {

      },),
      body: new Container()
    );
  }
}
class _CenterDockedFloatingActionButtonLocation extends _DockedFloatingActionButtonLocation {
  const _CenterDockedFloatingActionButtonLocation();

  @override
  Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    final double fabX = (scaffoldGeometry.scaffoldSize.width - scaffoldGeometry.floatingActionButtonSize.width) / 2.0;
    return Offset(fabX, getDockedY(scaffoldGeometry));
  }
}

abstract class _DockedFloatingActionButtonLocation extends FloatingActionButtonLocation {
  const _DockedFloatingActionButtonLocation();
  @protected
  double getDockedY(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    final double contentBottom = scaffoldGeometry.contentTop;
    final double appBarHeight = scaffoldGeometry.bottomSheetSize.height;
    final double fabHeight = scaffoldGeometry.floatingActionButtonSize.height;
    final double snackBarHeight = scaffoldGeometry.snackBarSize.height;

    double fabY = contentBottom - fabHeight / 2.0;
    if (snackBarHeight > 0.0)
      fabY = math.min(fabY, contentBottom - snackBarHeight - fabHeight - kFloatingActionButtonMargin);
    if (appBarHeight > 0.0)
      fabY = math.min(fabY, contentBottom - appBarHeight - fabHeight / 2.0);

    final double maxFabY = scaffoldGeometry.scaffoldSize.height - fabHeight;
    return math.min(maxFabY, fabY);
  }
}
like image 64
a0x2 Avatar answered Sep 19 '25 08:09

a0x2