Skip to content

Instantly share code, notes, and snippets.

@hectorAguero
Last active September 5, 2024 15:00
Show Gist options
  • Save hectorAguero/ac22b5a14a397be1a1fe4af1be07e193 to your computer and use it in GitHub Desktop.
Save hectorAguero/ac22b5a14a397be1a1fe4af1be07e193 to your computer and use it in GitHub Desktop.
Widget code order
// 1. Imports (if any)
import 'package:flutter/material.dart';
// 2. Enums
enum DSAppBarType { primary, secondary, tertiary }
enum DSAppBarSize { xs, s, m, l }
// 3. StatefulWidget class
class DSAppBarWidget extends StatefulWidget {
const DSAppBarWidget({
super.key,
required this.type,
required this.title,
this.size = DSAppBarSize.s,
});
final DSAppBarType type;
final DSAppBarSize size;
final String title;
@override
State<DSAppBarWidget> createState() => _DSAppBarWidgetState();
}
// 4. State class
class _DSAppBarWidgetState extends State<DSAppBarWidget> {
// 4a. Private fields
bool _isPressed = false;
// 4b. Lifecycle methods
@override
void initState() {
super.initState();
// TODO: implement initState
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
}
// 4c. Build method
@override
Widget build(BuildContext context) {
final properties = _getProperties();
return InkWell(
onTap: _validatePressed,
child: Container(
height: properties.height,
color: properties.color,
child: AppBar(
title: Text(widget.title),
),
),
);
}
// 4d. Private methods
void _validatePressed() {
setState(() {
_isPressed = !_isPressed;
});
}
_DSAppBarProperties _getProperties() => switch (widget.type) {
DSAppBarType.primary => _DSAppBarProperties(height: widget.size.height, color: Colors.black),
DSAppBarType.secondary => _DSAppBarProperties(height: widget.size.height, color: Colors.black12),
DSAppBarType.tertiary => _DSAppBarProperties(height: widget.size.height, color: Colors.red)
};
}
// 5. Extensions
extension DSAppBarSizeExtension on DSAppBarSize {
double get height => switch (this) {
DSAppBarSize.xs => 24,
DSAppBarSize.s => 32,
DSAppBarSize.m => 40,
DSAppBarSize.l => 48,
};
}
// 6. Helper classes
class _DSAppBarProperties {
_DSAppBarProperties({required this.height, required this.color});
final double height;
final Color color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment