Add rating to book details
Presentation (Building the UI)
Summary
This lesson focuses on reusing the existing BookRating widget within the book details screen. The instructor demonstrates how to make the widget flexible by accepting a MainAxisAlignment parameter, allowing it to be left-aligned in lists and centered in the details view. Additionally, the video covers refining the widget's visual fidelity against the Adobe XD design by adjusting font weights, icon sizes, and replacing hardcoded text colors with an Opacity widget.
Key Ideas
- Widget reuse reduces code duplication by leveraging the previously built
BookRatingcomponent across different screens. - Constructor parameters, such as
MainAxisAlignment, allow shared widgets to adapt their layout context without duplicating code. - Opacity widgets provide a more accurate representation of semi-transparent design elements than hardcoded color picking.
- Icon sizes and spacing often require manual tuning to match design specifications when using default icon libraries like FontAwesome.
- Design files specify layout constraints (like an 18px height gap) that dictate the
SizedBoxvalues used between UI elements. - Exporting custom icons as SVG is recommended when standard library icons diverge too much from the design, though adjusting the
sizeproperty can be a quick alternative.
Code Snippets
class BookRating extends StatelessWidget {
const BookRating({
super.key,
this.mainAxisAlignment = MainAxisAlignment.start,
});
final MainAxisAlignment mainAxisAlignment;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: mainAxisAlignment,
children: [
const Icon(
FontAwesomeIcons.solidStar,
color: Color(0xffFFDD4F),
size: 14,
),
const SizedBox(
width: 6.3,
),
Text(
'4.8',
style: Styles.textStyle16.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(
width: 5,
),
Opacity(
opacity: .5,
child: Text(
'(2390)',
style: Styles.textStyle14,
),
),
],
);
}
}const SizedBox(
height: 18,
),
const BookRating(
mainAxisAlignment: MainAxisAlignment.center,
),My Notes
The instructor correctly emphasizes widget reusability by parameterizing BookRating. A great takeaway is the correction on how to handle text color variations. Previously, the instructor color-picked a blended grey, but checking the design revealed it was actually pure white with 50% opacity. Using Opacity is generally more responsive to theme changes (like Dark/Light mode) than hardcoding a blended hex code.
- [Editor's note] While
Opacityis fine here, wrapping text in anOpacitywidget forces a new layer during rendering. For simple text color transparency, it is slightly more performant to use.withOpacity(0.5)directly on theColorinside theTextStyle. - [Editor's note] The instructor manually overrides the font weight to
w600despite the design saying "regular". This is a common reality in Flutter UI development where font rendering engines differ slightly from design tools.