Flutter Diamond/Rhombus shaped FloatingActionButton
In this tutorial, we will learn how to change the shape of Flutter FloatingActionButton to Rhombus/Diamond.
By default, Flutter does not have any shape like Diamond to apply for the background of FloatingActionButton. But, we can achieve this feat, by drawing a Custom Shape for the background of FloatingActionButton.
Example – Draw Diamond Shape Background for FloatingActionButton
Let us create a basic Flutter Application and replace the main.dart file with the following code.
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Text("Flutter Tutorial - googleflutter.com"),
),
floatingActionButton: FloatingActionButton(
onPressed: (){},
child: Icon(Icons.refresh),
shape: _DiamondBorder(),
),
);
}
}
class _DiamondBorder extends ShapeBorder {
const _DiamondBorder();
@override
EdgeInsetsGeometry get dimensions {
return const EdgeInsets.only();
}
@override
Path getInnerPath(Rect rect, { TextDirection textDirection }) {
return getOuterPath(rect, textDirection: textDirection);
}
@override
Path getOuterPath(Rect rect, { TextDirection textDirection }) {
return Path()
..moveTo(rect.left + rect.width / 2.0, rect.top)
..lineTo(rect.right, rect.top + rect.height / 2.0)
..lineTo(rect.left + rect.width / 2.0, rect.bottom)
..lineTo(rect.left, rect.top + rect.height / 2.0)
..close();
}
@override
void paint(Canvas canvas, Rect rect, { TextDirection textDirection }) {}
// This border doesn't support scaling.
@override
ShapeBorder scale(double t) {
return null;
}
}
Screenshot
What happened over here?
In this Flutter Application, we created a new class named _DiamondBorder that extends ShapeBorder class. _DiamondBorder class has to implement some of the abstract methods of ShapeBorder. Of them, getOuterPath() is the method that we are interested in. Following is the method that we used in the above example.
Path getOuterPath(Rect rect, { TextDirection textDirection }) {
return Path()
..moveTo(rect.left + rect.width / 2.0, rect.top)
..lineTo(rect.right, rect.top + rect.height / 2.0)
..lineTo(rect.left + rect.width / 2.0, rect.bottom)
..lineTo(rect.left, rect.top + rect.height / 2.0)
..close();
}
If you observe the code, we started at left corner of the diamond, and drawn a line to each of the corners in clockwise direction.
You can also create shape borders customized to your requirement.
Summary
In this Flutter Tutorial, we learned how to make the border shape of FloatingActionButton as Diamond, with the help of well detailed example Flutter Application.