如何在颤振中将自定义偏移设置为在脚手架中"FloatingActionButtonLocation"?



最近推出了FloatingActionButtonLocation,它有四个值,全部用于底部对齐。我想把它放在顶部,在应用程序栏的一半下面。但我不知道如何设置自定义偏移。这方面的官方文件也很少。

这违反了材料设计准则。但您可以通过将scaffoldGeometry.contentBottom从原始源代码更改为scaffoldGeometry.contentTop来实现这一点。以下代码应工作

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);
}
}

不要使用内置的FAB,而是使用一个带有自己的圆形按钮的堆栈。在脚手架的内部,你可以这样做:

body: Stack(
children: <Widget>[
Container(
// whatever your main content is
),
Positioned(
top: 5.0,
right: 200.0, // or whatever
child: MyFAB,
),
],
),

然后MyFAB可以是这样的:

class MyFAB extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.blue,
child: InkWell(
onTap: () => {},
borderRadius: BorderRadius.circular(50.0),
child: Container(
width: 45.0,
height: 45.0,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
child: Icon(
Icons.add,
color: Colors.yellow,
size: 25.0,
),
),
),
);
}
}

现在,您可以使用Stack中的Positioned小部件将FAB定位到任何您想要的位置。

最新更新