Logo

dev-resources.site

for different kinds of informations.

Building a Custom Flutter Widget from Scratch

Published at
6/21/2024
Categories
flutter
custom
widgets
Author
harsh8088
Categories
3 categories in total
flutter
open
custom
open
widgets
open
Author
9 person written this
harsh8088
open
Building a Custom Flutter Widget from Scratch

Flutter's magic lies in its extensive widget library. But what if you need a UI element that doesn't quite fit the mold? That's where custom widgets come in! Buckle up, Flutter developers, as we embark on a journey to build a custom widget from scratch.

Why Custom Widgets?

Custom widgets offer a treasure trove of benefits:

  • Reusability: Write your widget once, use it everywhere! This saves code, promotes consistency, and streamlines development.
  • Encapsulation: Package functionality and appearance into a neat unit, keeping your code clean and organized.
  • Customization: Tailor your widget's behavior and appearance to precisely meet your needs.

Let's Build a Star Rating Widget!

Imagine a widget that displays a row of stars, allowing users to rate something. Here's how we'll break it down:

1. Setting Up:

Create a new Flutter project and a dedicated Dart file for your widget (e.g., custom_rating_bar.dart).
Import necessary packages like flutter and material.

2. The CustomStarRating Class:

Define a class named CustomRatingBar that extends StatelessWidget.

3. Star Count and Rating Properties:

Add properties to the CustomRatingBar class:
starCount: An integer representing the total number of stars.
rating: A double representing the current user rating (optional).
filledColor: Color representing the filled color for the star.
unfilledColor: Color representing the unfilled color for the star.

4. Building the Stars:

Override the build method of the CustomRatingBar class.
Use a Row widget to display the stars horizontally.
Loop through a list based on starCount.
Inside the loop, use an Icon for each star.
Customize the Icon displayed based on the current rating (filled star for selected, unfilled star for unselected).

5. Handling User Interaction:

Set the onTap callback of the GestureDetector to update the rating property.
Consider emitting an event (using a ValueNotifier or similar) to notify parent widgets about rating changes.

6. Adding Flair (Optional):

Style your stars using Icon properties like color and size.
Implement custom animations for star selection using AnimatedIcon.

Putting it All Together:

With all the pieces in place, use the CustomRatingBar widget in your app's layout:

CustomRatingBar(starCount: 5, rating: 1.0,
                filledColor: Colors.amber,
                unfilledColor: Colors.grey,
                onRatingChanged: () {})
Enter fullscreen mode Exit fullscreen mode

custom_rating_bar.dart

import 'package:flutter/material.dart';

class CustomRatingBar extends StatefulWidget {
  final double rating;
  final int starCount;
  final Function onRatingChanged;
  final Color filledColor;
  final Color unfilledColor;

  const CustomRatingBar({
    super.key,
    required this.rating,
    required this.starCount,
    required this.onRatingChanged,
    required this.unfilledColor,
    required this.filledColor,
  });

  @override
  State<CustomRatingBar> createState() => _CustomRatingBarState();
}

class _CustomRatingBarState extends State<CustomRatingBar> {
  double _currentRating = 0.0;

  @override
  void initState() {
    super.initState();
    _currentRating = widget.rating - 1;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: List.generate(
        widget.starCount,
        (index) => GestureDetector(
          onTap: () => _onStarTap(index.toDouble()),
          child: Icon(
            Icons.star,
            size: 30.0,
            color: _getColor(index),
          ),
        ),
      ),
    );
  }

  Color _getColor(int index) {
    if (index <= _currentRating) {
      return widget.filledColor;
    } else {
      return widget.unfilledColor;
    }
  }

  void _onStarTap(double newRating) {
    if (_currentRating == newRating) {
      newRating--;
    }
    setState(() {
      _currentRating = newRating;
      // widget.onRatingChanged(newRating);
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This blog demonstrates a basic implementation of a custom rating bar in Flutter. It offers features like:

Star Count: You can easily adjust the number of stars displayed.
Rating: Users can tap on stars to provide their rating.
Colors: Define the desired colors and icons for filled, empty, and half-filled states (if applicable).

Further Enhancement Scopes

  • Animated Selection: The selected stars smoothly animate with a scaling effect.
  • Half Rating Support: Modify the function to include logic for displaying half-filled stars.

GitHub Code

Happy Coding!!! πŸ§‘πŸ»β€πŸ’»

custom Article's
30 articles in total
Favicon
Custom Website Development - A Complete Guide for Small Businesses
Favicon
What Are the Steps Involved in Developing a Custom AI Solution?
Favicon
How Will Custom EMR EHR Software Reshape the Healthcare Horizon?
Favicon
The Ultimate Guide to Custom T-Shirts: Unique, Creative, and Personalized
Favicon
Custom Bottle Neckers for Sale Wholesale and Printed Options
Favicon
Order Custom Bottle Neckers Wholesale for Packaging Needs
Favicon
Custom CBD Boxes Wholesale with Logo for Premium Branding
Favicon
How to Build a Secure and Profitable DeFi Staking Platform
Favicon
Power of Custom Product Packaging: Enhancing Brand Experience and Driving Sales
Favicon
How to add custom fonts and viewports in storybook?
Favicon
How to choose the right service app for your needs | Optimity Logics
Favicon
Vue Vs Angular: Which One Should You Choose for Your Project? | Optimity Logics
Favicon
Transform Your Branding with 3M Printable Vinyl Wraps in Deltona, FL
Favicon
This Single-Line Command Reduced Our Database Object Management Efforts
Favicon
Custom Website Design Benefits
Favicon
Elevate Gift Giving With Custom Pillow Boxes For Every Occasion
Favicon
Creating a Custom 404 Not Found Page in Next.js 14
Favicon
How Cloud-Native Development is Redefining Custom Software Solutions?
Favicon
Boost Your Sales with a Custom Virtual Store: Here’s How
Favicon
DOM Selection with Custom Function
Favicon
When it comes to interior design in Dubai
Favicon
Building a Custom Flutter Widget from Scratch
Favicon
The Ultimate Guide to Choosing the Right Custom Sunglasses Manufacturer for Your Brand
Favicon
Laravel 11 Custom Component File Structure
Favicon
Secure Your Online World for Under $6: Why You Need a Personal VPN
Favicon
Streamline Your Django Workflow: A Guide to Creating Custom Management Commands
Favicon
5 Software Development Tips to Improve Your Product Growth
Favicon
Desenhos complexos com CustomPaint
Favicon
Desenhe o que quiser com Custom Paint no Flutter
Favicon
How to create a custom VSCode theme

Featured ones: