Let’s learn how to make a custom divider using Flex, List.generate() and LayoutBuilder() in flutter. We will wrap everything inside LayoutBuilder() and it has builder property.
Inside LayoutBuilder‘s builder property we will return Flex and inside Flex we will return List.generate().
We will create a class named CustomDivider() and it will named optional parameters. The default value would height = 1 and color would be black.
Since this is a complete dynamic way of doing custom divider, we used LayoutBuilder() to get width of the parent.
Different devices will have different width for UI. LayoutBuilder() will help us get that width.
LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final boxWidth = constraints.constrainWidth();
.........................................................................
boxWidth is the actually the width of the UI.
Based on boxWidth we count the dashCount. Number of dashes we want to show on the UI.
final boxWidth = constraints.constrainWidth();
final dashWidth = 5.0;
final dashHeight = height;
final dashCount = (boxWidth / (2 * dashWidth)).floor();
Number of dashCount depends on the boxWidth and dashWidth. dasWidth you can set to based on your needs.
dashCount, helps us to be used in List.generate(). List.generate() needs to know how many times a loop should run.
void main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primaryColor: Colors.blue,
fontFamily: "Lato",
),
home: Scaffold(
backgroundColor: Colors.white,
body: Center(
child: CustomDivider(),
),
),
);
}
}
class CustomDivider extends StatelessWidget {
final double height;
final Color color;
const CustomDivider({this.height = 1, this.color = Colors.black});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final boxWidth = constraints.constrainWidth();
final dashWidth = 5.0;
final dashHeight = height;
final dashCount = (boxWidth / (2 * dashWidth)).floor();
return Flex(
children: List.generate(dashCount, (_) {
return SizedBox(
width: dashWidth,
height: dashHeight,
child: DecoratedBox(
decoration: BoxDecoration(color: color),
),
);
}),
mainAxisAlignment: MainAxisAlignment.spaceBetween,
direction: Axis.horizontal,
);
},
);
}
}
List.generate()