Edit Content

Menu

Info

Flutter animation

Flutter Animation Explained

Flutter is an incredibly robust and dynamic framework that empowers developers to craft visually stunning and captivating mobile applications.  This framework stands out thanks to Flutter Animation’s exceptional capability to produce captivating animations that elevate the overall user experience.  Flutter animation offers a comprehensive suite of resources for enhancing mobile application user experience (UX) by imbuing the user interface (UI) with seamlessness and authenticity.  Let’s explore some fundamentals of Flutter animations with a Flutter animation tutorial. Flutter Animations-An Overview  Using Flutter Animation, programmers can easily design interactive and aesthetically pleasing user interfaces.  Animation in Flutter is like a visual illusion of motions made from images, widgets, or routes.  To create an animation in Flutter, you define the initial and final states of an object or property and then tell it how to interpolate between them.  Flutter Animation’s ease of use and adaptability are two of its most appealing qualities. It’s simple for developers to animate everything from simple buttons and icons to more complex widgets and snippets of text. The user experience can be fine-tuned by adjusting animation length, easing curves, and playback.  Other Flutter features, such as gesture detection and user input, work harmoniously with Flutter Animation. What Are The Different Types Of Flutter Animations? Flutter has many animations to bring your app to life. Fade, scale, rotate, implicit, and explicit animations are among these. Understanding animation types will help you choose one for your app. Fade Animation flutter: This animation allows you to smoothly transition an element from being fully visible to completely invisible, or vice versa.  Scale animation: This animation allows you to smoothly resize an element, making it appear larger or smaller.  Rotate animation:  This flutter animation allows you to rotate an element around a specified axis smoothly. It can create exciting effects, such as rotating a card when flipped or adding a playful touch to your app by animating a spinning logo. Implicit: Flutter’s implicit animations are the animated transitions that happen mechanically whenever a widget’s property is updated. If you want a seamless transition between a widget’s old and new values, you may use an implicit animation when you alter its color or size. Explicit: Explicit animations are preferred when you need to construct unique animations with fine-grained control over individual animation parameters, but they need more manual input. Common techniques include tweens, animation controllers, and animated widgets to manipulate the animation process directly. Flutter Animation Example  When pressed, a button in your Flutter app should trigger an animation. Let’s make something exciting and valuable to showcase the potential of Flutter Animation.  We want the button’s size to increase and decrease gradually, and its color will shift from gray to blue, then blue to grey when the user presses it. Flutter Animations can be used to create this effect. To begin, we establish a Flutter Animation Controller that manages the looping and stopping of the animation. To define the range of values for resizing and coloring, we’ll use a Tween. Once the button is pressed, we invoke the forward method of the AnimationController to begin the animation. We use Tween’s interpolated values to change the size and color of the button throughout the animation. import ‘package:flutter/material.dart’; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: ‘Animations’, theme: ThemeData( primarySwatch: Colors.purple, appBarTheme: const AppBarTheme(centerTitle: true), ), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { late AnimationController _animationController; late Animation<double> _scaleAnimation; late Animation<Color?> _colorAnimation; @override void initState() { const duration = Duration(milliseconds: 500); _animationController = AnimationController(duration: duration, vsync: this); _scaleAnimation = Tween<double>( begin: 1.0, end: 2.0, ).animate(_animationController); _colorAnimation = ColorTween( begin: Colors.grey, end: Colors.blue, ).animate(_animationController); super.initState(); } @override void dispose() { _animationController.dispose(); super.dispose(); } Future<void> _onButtonPressed() async { await _animationController.forward(); await _animationController.reverse(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text(‘Animations’)), body: Center( child: AnimatedBuilder( animation: _animationController, builder: (context, child) { return Transform.scale( scale: _scaleAnimation.value, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: _colorAnimation.value, ), onPressed: _onButtonPressed, child: const Text(‘Like’), ), ); }, ), ), ); } } How To Make An Animated Widget In Flutter? Here is how you can add an animated widget in the Flutter application:  Define a stateful Widget: Create a new class in your Dart file that inherits from StatefulWidget. Identify your stateful widget with this class. Define a new class in this file that inherits from the State class. This class will manage your widget’s state and logic. Define the animation: Set up an AnimationController inside the State class of your StatefulWidget. With this controller, you can change how long your animation lasts and how it plays. You can choose the length of time and other properties. Implement the animation logic: Override the initState() method inside the State class. Inside this method, you can set up the AnimationController and tell it how to move using Animation or Tween objects. You can choose from different animations, such as fading in, sliding, or scaling. Build the animated widget: You can use the AnimatedBuilder widget in your widget’s build() method to add animations. Return the widget you want to animate inside the builder function of AnimatedBuilder. Update the animation: The animation can be triggered by invoking forward(), reverse(), or repeat() on the animation controller. These methods can be called in response to input from the user or other events. import ‘package:flutter/material.dart’; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: ‘Animations’, theme: ThemeData( primarySwatch: Colors.purple, appBarTheme: const AppBarTheme(centerTitle: true), ), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _scaleAnimation; @override void initState() { super.initState(); const duration = Duration(seconds: 2); _controller = AnimationController(duration: duration, vsync: this); _scaleAnimation = Tween<double>( begin: 1.0, end: 2.0, ).animate(_controller); _controller.repeat(); } @override void dispose() {

Read More »
flutter google fonts

Flutter Google Fonts: Custom Font Made Easy

If you want to make your Flutter application more appealing and in control, Flutter Google fonts are at your service. Google offers a vast library of Google fonts which are free and accessible and can be used in mobile application development to make your typography more remarking. Flutter, a Google UI toolkit, also supports Google Fonts, enabling developers to integrate high-quality and readable Google Fonts in Flutter applications.  You can use various available fonts in the library by implementing the Google_fonts package.  Come and dig a little deeper into how the google font flutter works and what are the available fonts.  What is Flutter Google Fonts?  Google Fonts is a remarkable package that streamlines the seamless integration of exquisite custom fonts sourced from the extensive Google Fonts collection into your Flutter applications. When installed, the app conveniently downloads the font files to the user’s device. This feature allows users to enjoy uninterrupted access to a wide range of fonts, regardless of their internet connectivity status. What is the difference between font family and font style? Font Family A font family is a group of fonts with a cohesive design that offers distinct styles, weights, or variations. Regarding font families, it’s essential to consider the various variations available for a specific typeface. These variations typically include regular, bold, and italic styles. In typography, it is customary to designate every distinct iteration within a font family as a “font.” Font Style Font styles in Flutter are the individualized presentation of a Flutter font family. Features such as weight (normal, bold), style (italic), and flutter font size (12 pixels, 16 pixels, etc.) are all accounted for. The font style determines the text’s size, alignment, and weight.  There are four types of typefaces:  Serif Sans serif script Decorative  Flutter Google Fonts List  Have you ever wondered What fonts Flutter has? A wide selection of Flutter Google fonts allows developers to select from a diverse range of typefaces that cater to various design requirements, including classic, modern, and playful aesthetics. Furthermore, the implementation of Google Fonts in the Flutter framework is specifically designed to enhance the visual appeal of typography in web and mobile applications, guaranteeing a high-quality rendering of text across various devices.  Although there are numerous variations of Google fonts available, the most common are given below:  Roboto Lato  Open Sans  Montserrat Oswald Raleway Quicksand   Poppins Nunito  Ubuntu  Custom Font Flutter  Although Android and iOS applications are built with high-quality fonts, designers still demand custom fonts. Depending on the user’s preference, Flutter supports the custom font flutter on an individual widget across the application. Here’s how you can do it:  Add your custom font files to your Flutter project. Place the font files (e.g., .ttf or .otf) in a directory within your project’s folder structure (e.g., assets/fonts/). Register the font files in your pubspec.yaml file. Open the pubspec.yaml file and add the following code under the ‘flutter’s assets’ section. fonts: – family: <Font-Family-Name> fonts: – asset: assets/fonts/<Font-Name>.otf – asset: assets/fonts/<Font-Name>.ttf Run the command flutter pub get into your terminal to fetch the font assets. In your Flutter code, import the package:flutter/services.dart package. Load the custom font family. Add the following code before your void main() function. Replace ‘assets/fonts/YourCustomFont-Regular.ttf’ and ‘assets/fonts/YourCustomFont-Bold.ttf’ with the appropriate file paths for your custom font files. void main() async { WidgetsFlutterBinding.ensureInitialized(); await loadFont(); runApp(MyApp()); } Future<void> loadFont() async { await Future.wait([ // Load your custom font files rootBundle.load(‘assets/fonts/YourCustomFont-Regular.ttf’), rootBundle.load(‘assets/fonts/YourCustomFont-Bold.ttf’), ]); } Use the custom font in your Text widgets. Apply the custom font to any Text widget by setting the fontFamily property. Text( ‘Custom Font Example’, style: TextStyle( fontFamily: ‘CustomFont’, fontSize: 20, fontWeight: FontWeight.bold, ), ), Note: you can skip steps 4 and 5 and use step 6 directly. These steps are added to assist newbies or beginners. How to Choose a Font Family in Flutter? Here is the simplest way to choose a font family in Flutter:  The first and prime step to use the google_fonts package in the Flutter app is to add the google_fonts to your project. You can do this by mentioning the google_fonts package and its version in the ‘pubspec.yaml’ file. Then run the ‘flutter pub get’ command at the terminal to download the google_fonts package. dependencies: google_fonts: ^5.1.0 The next step is to import the google_fonts library. To utilize the fonts in your Dart file, initially import the Google Fonts library. import ‘package:google_fonts/google_fonts.dart’; The GoogleFonts class can be utilized to access the font families that are currently available. Users can select from a diverse range of font families available through Google Fonts, or alternatively, they may opt to utilize a custom font. Now you can access the Google Fonts Family by using this syntax. import ‘package:flutter/material.dart’; import ‘package:google_fonts/google_fonts.dart’; Text( ‘Hello’, style: GoogleFonts.<Font-Name>( fontSize: 20, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, ), ), Just replace this <Font-Name> with your desired font name, like Poppins, inter, etc, and that font will be applied to your text.  Using Google Fonts in Flutter Offline  To use the google fonts offline, you have to follow the following steps to get an uninterrupted experience:Visit the Google Fonts website (https://fonts.google.com/) using a web browser. Browse and select the desired font(s) for your project. Click on the selected font(s) to open the font details. Click the “Download family” button on the font details page. Extract the downloaded zip file to use the font files (usually in .ttf or .otf format). Create a new folder named fonts in your Flutter project’s root directory. Copy the downloaded font files (.ttf or .otf) into the fonts folder. Changing Font Dynamically  With flutter google fonts, you can also change the font style as per your preference. Follow the same steps till selecting the font family, then proceed with the following steps: When you want to change the font dynamically, update the value of the selectedFontFamily variable with the desired font family. To reflect the font change, you need to rebuild the widget tree using setState method if you’re changing the font based on user interaction, such

Read More »

Flutter Spinkit: Loading Indicator Animations

Have you ever wondered where these animations on Flutter come from while your application is progressing any command? This is what the loading indicator or, more specifically, flutter spinkit does. There are various forms of loading indicator animations that get displayed on your screen while your data is being fetched. These animations enhance the user’s experience while using the application. Flutter SpinKit, or Spinner Kit, provides multiple premade animations to add to your application’s code. It means spinkit in flutter and other loading indicators add to the animations making your application more appealing and engaging to the user. Let’s start with a brief guide on loading indicators in Flutter and how flutter_spinkit can be used. Brace yourself, readers; it will be too much informative and fun. What Are The Loading Indicators In Flutter Spinkit? Indicators in Flutter are visual elements displayed on your screen each time your application wants to indicate the status of the requested command. For example, a spinning circle indicates the loading progress if you are loading something on your application. Flutter loader can be in the form of text stating your progress percentage. These indicators or Flutter loaders come with the advantage of preventing any further command from being fetched while running any asynchronous operation. The purpose of a loading indicator is to provide visual feedback and reassure users that the app is actively working on their requests. It is not intended to restrict or prevent user interactions but to communicate that an ongoing operation is ongoing. Types of Loading Indicators Generally, there are three types of Indicators in Flutter: Loading indicators These circular or text-based animations depict the task’s progress that will take a while to complete. Progress indicators The progress indicator is a more detailed animation showing the percentage of the completed task. Refresh Indicators  When a refresh action is triggered in Flutter, such as when the user pulls down on a scrollable view to refresh the contents of that view, refresh indicators give the user a visual indication of what has happened. It will typically display a progress indicator as a spinning circular bar or some other animation to indicate that the refresh procedure is occurring. Flutter Spinkit Library Flutter Spinkit is a library of premade and customizable loading indicators for Flutter application development. If spinkit were not there, you would have to manually add the indicators within the code, which requires both the skillset and expertise in coding. But with Spinkit Flutter, the premade indicators save you the effort. How Do You Make A Loading Spinner In Flutter? With the spinkit library, creating a loading spinner in Flutter is no more a daunting task. You have to follow the following steps to add the flutter spinkit package library: The first and prime step to use the flutter_spinkit package in the Flutter app is to add the flutter_spinkit to your project. You can do this by mentioning the flutter_spinkit package and its version in the ‘pubspec.yaml’ file. Then run the ‘flutter pub get’ command at the terminal to download the flutter_spinkit package. dependencies: flutter_spinkit: “^5.2.0”  The next step is to import the spinkit library. To utilize the spinner in your Dart file, import the SpinKit library initially. import ‘package:flutter_spinkit/flutter_spinkit.dart’; Now comes the use of the Flutter Spinkit Widget. Integrate SpinKit widgets into your code effortlessly. To utilize the RotatingCircle spinner, simply include it in your project. Discover a variety of SpinKit widgets that offer unique animations, including SpinKitFadingCircle, SpinKitCubeGrid, SpinKitDoubleBounce, and more. Easily swap out SpinKitCircle for a fresh look and feel. SpinKitCircle( color: Colors.blue, size: 50.0, ) This is the visual representation of how the loading spinner circle works:   Here is a brief example of using flutter_spinkit in your app. import ‘package:flutter/material.dart’; Import ‘package:flutter_spinkit/flutter_spinkit.dart’; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: ‘Flutter Spinkit’, home: const HomePage(), ); } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text(‘Flutter Spinkit’)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Text(‘SpinKitRotatingCircle’), SizedBox(height: 8), SpinKitRotatingCircle(color: Colors.black), Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text(‘SpinKitFadingCircle’), ), SpinKitFadingCircle(color: Colors.black), Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text(‘SpinKitCubeGrid’), ), SpinKitCubeGrid(color: Colors.black), Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text(‘SpinKitDoubleBounce’), ), SpinKitDoubleBounce(color: Colors.black), Padding( padding: EdgeInsets.symmetric(vertical: 8.0), child: Text(‘SpinKitCircle’), ), SpinKitCircle(color: Colors.black), ], ), ), ); } }   Flutter Packages To Improve Your Animation Skills To get an expert hold on the animations while using the Flutter package, you can use the following packages: Flutter Animate: Discover a variety of animation widgets available at this library, perfect for adding dynamic movement to your Flutter applications. This offers a variety of animation options, such as FadeIn, FadeOut, SlideUp, SlideDown, and more, to enhance the appearance and disappearance of your widgets. Animate Text Kit: This package offers animation options explicitly tailored for text. Enhance your text elements with various effects, including typewriter, fade, rotate, and more. It’s effortless to add these effects to your text. Flutter Sequence Animation: You can construct intricate animation sequences with this program. It can define and run multiple tweens on a single animation controller in sequence or parallel. Flutter Spinkit: This flutter animation package offers a wide range of pre-built loading animations that can be easily integrated into your application. Animate Do: This robust package integrates stunning animations into your Flutter applications. Flutter’s animation capabilities are enhanced with the Animate.css library, which offers a wide range of robust animations, including bouncing, fading, flipping, and more. Animations: The animations package features a variety of pre-built animations such as Container Transform, Shared Axis, Fade Through, and Fade. These animations can be easily integrated into your app to enhance its visual appeal and user experience. Tips for Flutter Spinkit Always ensure that your  Flutter Spinkit is visible against the background. If your Spinkit color is similar to the background, it might be hard to notice. This property can be used to show or hide the Spinkit based on whether the

Read More »

Flutter Gesturedetector: Mastering Gestures Guide

When it comes to controlling the gestures within the application, managing user gestures as per the user’s feedback is of prime importance; this is what GestureDetector Flutter is destined for. You can recognize gestures like taps, drags, dropdowns, and swipes using the GestureDetector widget, and you can apply custom logic to the motions to determine how they should be handled. This article will briefly explain what Flutter GestureDetector is and how it handles all the gestures within the Flutter-made application. What Is Flutter GestureDetetor? The GestureDetector in Flutter is a non-visible widget that manages all gestures made within an application. Gestute is a specific action made by the user to give a specific command to the device.  Common gestures in Flutter include: Tapping Dragging LongPressing Widgets like cards and containers cannot detect the gesture(s). They are generally wrapped with GestureDetector to execute the gesture made; however, unlike InkWell Flutter, it does not display any visual effect in the form of a ripple effect. GestureDetector Flutter only responds to those gestures with predefined callbacks. With the child, it fits the size of the child for sizing. While if there is no child, it grows to the size of its parent. To disable this widget, you must make a null value to the callback. Flutter GestureDetector Example In this example, we will learn how to use GestureDetector in Flutter around the Container border flutter widget. To use the Flutter GestureDetector, you must first import the ‘materia.dart’ package. The GestureDetector takes a child and a callback. In this example, we use Container as a child, and we use an onTap callback. When we tap on the Container, a SnackBar will pop up from the bottom of the screen with the message ‘Tap!’. import ‘package:flutter/material.dart’; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text(‘GestureDetector Example’), ), body: const Center(child: MyGesture()), ), ); } } class MyGesture extends StatelessWidget { const MyGesture({super.key}); @override Widget build(BuildContext context) { // GestureDetector wraps the button return GestureDetector( // When the child is tapped onTap: () { const snackBar = SnackBar(content: Text(‘Tap!’)); // Find the ScaffoldMessenger in the widget tree // and use it to show a SnackBar ScaffoldMessenger.of(context).showSnackBar(snackBar); }, // Our GestureDetector wraps a Container child: Container( padding: const EdgeInsets.all(12.0), decoration: BoxDecoration( color: Theme.of(context).primaryColor, borderRadius: BorderRadius.circular(8.0), ), child: const Text( ‘Tap me’, style: TextStyle(color: Colors.white), ), ), ); } } Here is the video representation of the code: Other gestures or callbacks which you can have other than ‘onTap’ are: Gestures in GestureDetector Flutter Description  onDoubleTap Triggered when the user taps the widget twice within a specific time frame. onLongPress Triggered when the user presses or holds the screen for a specified duration. onSecondaryTap There has been a secondary button tap. This starts when the tap gesture succeeds. OnSecondaryTapCancel is called in its place if the tap gesture is unsuccessful. onLongPressDown The user must press and hold the screen for the specified time for this callback to be activated. When the lengthy press is noticed, it is just called once. onVerticalDragStart It is triggered when a vertical drag gesture is recognized and starts. onPanStart Regardless of the direction of the flutter drag, the onPanStart callback of the GestureDetector is activated whenever a pan gesture (dragging across the screen) is detected and begins. Scale-Up Gestures In Flutter GestureDetector These gestures are usually made in a Flutter when the user zooms in or out of the screen or enlarges it. Here is how to scale gesturedetector android works Following gestures are usually made in scale-up GestureDetector Flutter: onScaleStart: When the user initiates a scale gesture, the onScaleStart callback is activated. This callback is activated once when a user touches the screen for the first time with two fingers. onScaleUpdate: As the user scales the widget, the onScaleUpdate callback is continuously invoked. A ScaleUpdateDetails object containing details about the current scale factor is used to call this function.. onScaleEnd: When a user ends a scale gesture, the callback function onScaleEnd is activated. This callback is activated once the user lifts their finger off the screen. GestureDetector Navigation Flutter Flutter uses navigation widgets to navigate within different pages. These navigation widgets take charge of a stack of routes. When handling mobile applications, users invoke different GestureDetector swipe flutter gestures to navigate across the images. Flutter GestureDetectos take in all the navigation and invoke necessary callback gestures. Gesture Arena Flutter If you need more control over the gesture system, such as to recognize simultaneous gestures, you might need to use the lower-level GestureArena system or create your own GestureRecognizer. The GestureRecognizers identify particular motion patterns and receive touch events from the Flutter gesture system. When several recognizers are perhaps interested in the same touch event sequence, these recognizers compete in the GestureArena, which chooses the winner. Following are the steps to do it: Implementing a unique GestureRecognizer can be helpful if you want to identify a unique gesture. A GestureRecognizer receives several touch events and either recognize a particular gesture or forwards the events to other recognizers. Recognizers for multiple simultaneous gestures: The RawGestureDetector widget can detect multiple simultaneous gestures. You can do this by supplying your own recognizers and setting them up for simultaneous recognition. GestureRecognizer instances are created to accomplish this and connected via the team property. Direct control of the GestureArena flutter: If you require even greater control, you can direct the gesture arena. This lets you manually add or remove recognizers from the arena and choose which ones should triumph in challenging circumstances. Flutter GestureDetector Vs. InkWell Widget Though both useful widgets within Flutter handle the gesture interaction within the application, they still differ significantly in their functions. Regarding functioning, Flutter GestureDetector tackles the callbacks for various touch interactions. They handle all the non-visible outputs. Whereas InkWell Flutter adds a splash to the touch interaction and creates a ripple effect to make an impression on the user that your command

Read More »

Flutter File Picker: An In-depth Tutorial

The developer community has been buzzing about Flutter because of its mobile, desktop, and web applications possibilities. The ability of any application to pick files from the device while it is operating is its most notable feature. The performance of the particular program improves with smoother file selection. This is the point at which the Flutter file picker enters the picture. With this plugin, flutter file upload has been made easy. The native file explorer may now be explored and used for file selection using the Flutter file_picker package. You may conclude your work without any delays by using this plugin to rapidly locate any photographs, movies, or files on the device. Let’s look at how you use a file picker in Flutter and explain how it functions through a Flutter file picker example. Let’s begin working on it. What Is Flutter File Picker? Flutter file_picker is the plugin in Flutter that enables users to browse and select their desired files from the device. Flutter file_picker provides an accessible doorway to the user’s native file explorer for selecting multiple files. What Is The Difference Between An Image Picker Flutter And A file_picker In Flutter? Unlike the Flutter image picker, which only supports images or videos, the file_picker package offers multiple formats of files to be uploaded. As you give an open command prompt to your computer browser, the file_picker package brings that function to your application. 👉 How to add  cupertino date picker in flutter Features Of Flutter File Picker The following are the most prominent features of the Flutter file picker: With the file_picker package in Flutter, you can choose one or multiple files from your device. In addition to the number, it also supports multiple file types with custom format filtering. You can also limit the file type to your choice. For example, you can ask the application to select image-based files only. You can access multiple platforms with the same plugin, including Mobile, Desktop, Go-Flutter, or Web. The cloud files (iCloud, DropBox, or GDrive) are also available with Flutter file picker. Flutter File Picker Example For Web So far, you have a slight clearance on the flutter file picker; let’s move to how you use a flutter file picker. The following are the more straightforward steps: The first and prime step to use the file_picker package in the flutter is to add the flutter file_picker to your project. You can do this by mentioning the file_picker package and its version in the ‘pubspec.yaml’ file. Then run the ‘flutter pub get’ command at the terminal to download the file_picker package.   And to know the flutter command flow visit 👉“https://flutterdesk.com/waiting-for-another-flutter-command-to-release-the-startup-lock/“ dependencies: flutter: sdk: flutter file_picker: ^version 2. The next step is to import the added package to the dart file. import ‘dart:io’; import ‘package:file_picker/file_picker.dart’; import ‘package:flutter/foundation.dart’; import ‘package:flutter/material.dart’; 3. After you finish these two, you can use the Flutter file picker plugin class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { File? file; FilePickerResult? result; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text(‘File Picker’)), body: Center( child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ if (file != null || result != null) …[ if (kIsWeb) …[ Image.memory( result!.files.first.bytes!, height: 350, width: 350, fit: BoxFit.fill, ), ] else …[ Image.file(file!, height: 150, width: 150, fit: BoxFit.fill), ], const SizedBox(height: 8), ], ElevatedButton( onPressed: () async { try { result = await FilePicker.platform.pickFiles(); if (result != null) { if (!kIsWeb) { file = File(result!.files.single.path!); } setState(() {}); } else { // User canceled the picker } } catch (_) {} }, child: const Text(‘Pick File’), ), ]), ), ); } } The file_picker in this illustration is opened using FilePicker.platform.pickFiles(). This method waits for the user to select a file. A file_picker produces a FilePickerResult once a file has been selected, containing details about the selected file(s), using result.files.single.path, you can then create a File object by accessing the path of the chosen file. You may want to get a permit for multiple platforms, which restricts your capability to pick files from them. For this concern, you can use the ‘permission_handler’ package with the file_picke package. Flutter File Picker for Multiple Platforms For iOS For macOS For Windows For Android For Web For Linux Image Picker Flutter   The code mentioned above is to add file format from the device using Flutter file picker; what if you want to add image or Mp4 format? How can you add other formats with the File picker in Flutter: FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: [‘jpg’, ‘png’, ‘mp4’, ‘avi’], ); if(result != null) { File file = File(result.files.single.path!); } else { // User canceled the picker } This is the visual illustration of how the flutter image picker works: In the code mentioned above, we use ‘Filetype.custom’, which enables you to choose your desired file type extension. How To Get The File Path In The Flutter File Picker? Getting an SDK path to your file while using Flutter file picker is prime as it directs you to the path to the system’s file directory.  It is more like an address to your file directory, which you can use anytime to get redirected to the file’s location. import ‘package:file_picker/file_picker.dart’; void pickFile() async { FilePickerResult? result = await FilePicker.platform.pickFiles(); if(result != null) { String filePath = result.files.single.path!; print(filePath); } else { // User canceled the picker } } In this example, after the file is picked, ‘result.file.single.path’ gives you the path of the single selected file. Remember, these paths are platform-dependent and might require permission to run on others. Secondly, the path is always ‘null’ at the web Platform since the web has no access to the files directory. Conclusion With a flutter-made application, you can enable multiple features you wouldn’t have imagined with an application made with another framework. Like other plugins, flutter file picker brings the file-picking capability to the fingertips. It not just supports multiple formats but also assists in carrying the

Read More »

Inkwell Flutter:Key to Interactive UI Design

Where touch-based interaction increases the usefulness of an application, adding visual feedback makes the application more appealing. This is what Inkwell Flutter does to your application interfaces. Like several other widgets offered by Flutter, GestureDetector, and Flutter Inkwell are two widgets that respond to touch inputs. Inkwell Flutter is one step ahead of GestureDetector, which implements a material design ink splash on touch interactions. Let’s delve deep into how Inkwell Flutters’ ripple effect is created and how it enhances the user experience with mobile applications. What Is InkWell Flutter? Flutter Inkwell is a material widget in Flutter that responds to every touch user makes while using an application. It is more like a visual representation of what happens when we long-press or double-click the button. When we touch a button, it creates a ripple effect, like through a pebble within the water stream. It ensures the user that the application has received your command. Flutter Inkwell Class Flutter Inkwell class is a rectangular block of material widget that provides the area that responds to every touch. It initiates an immediate ripple response on the screen immediately after the touch. Using Inkwell With Material Widget To do this, you must wrap the  Flutter Inkwell widget with the Material widget. When you tap the Material widget, the Flutter Inkwell onTap function is called, and ‘Material widget tapped!’ will be printed on the console. After that, you can set a background color (in this case, the color is yellow) and select the container dimension to 100 pixels from both width and height. The Flutter Inkwell class always uses a material widget as an ancestor to ensure the ink is splashed rightly into the rectangular space. Material( color: Colors.yellow, child: InkWell( onTap: () { print(‘Material widget tapped!’); }, child: const SizedBox( width: 100.0, height: 100.0, child: Center(child: Text(‘Tap Me’)), ), ), ), You can also alter the highlight and splash colors according to your preference. In the following example, we have modified the Flutter Inkwell color, i.e., the splash color turns out red, and the highlight color is black. We have also adjusted the opacity of colors to enhance transparency. In the following example, we changed the red color (splash color) adjusted with 30% opacity while highlight colors have an opacity of 50%/ Here is how you can do it: Material( color: Colors.yellow, child: InkWell( onTap: () { print(‘Material widget tapped!’); }, splashColor: Colors.red.withOpacity(0.3), highlightColor: Colors.black.withOpacity(0.5), child: const SizedBox( width: 100.0, height: 100.0, child: Center(child: Text(‘Tap Me’)), ), ), ), We can also adjust the Inkwell Flutter shape by customizing the Inkwell Flutter shape just like the color. Generally, it appears as a rectangular block. We can use the ‘borderRadius’ or ‘customBorder’ property. Here is how you can do it: With customBorder Property:  Material( color: Colors.yellow, child: InkWell( customBorder: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), onTap: () { print(‘Material widget tapped!’); }, child: const SizedBox( width: 100.0, height: 100.0, child: Center(child: Text(‘Tap Me’)), ), ), ), Below is the inkwell flutter animation: With borderRadius Property:  Material( color: Colors.yellow, child: InkWell( borderRadius: BorderRadius.circular(50), onTap: () { print(‘Material widget tapped!’); }, child: const SizedBox( width: 100.0, height: 100.0, child: Center(child: Text(‘Tap Me’)), ), ), ) Below is the inkwell flutter animation for borderradius property: What is the Purpose of Inkwell in Flutter? Have you ever thought, What Inkwell Flutter is used for? Generally, InkWell manages the touch interactions within the application. The following are the purposes of the Inkwell Flutter Widget: When a user taps, long presses, or double taps on a widget, InkWell pays attention to their movements. It detects these motions and initiates the necessary callbacks, enabling you to react to user interactions. Other widgets, such as text, photos, or containers, can be wrapped in InkWell to make them interactive. As a result, you may design interactive UI elements. The InkWell ripple effect ensures that the widget complies with material design guidelines. Also Read – Mastering Dismissible in Flutter: Unlock the Power of Swipe Gestures Common Gestures In Inkwell Flutter Since Inkwell Flutter is all about touch interactions, it responds to the following gestures: onTap: this gesture is initiated when the user taps the widget. onLongPress: this gesture is initiated when the user presses the button and holds it for a while. onTapCancel: this gesture is not familiar, but It starts when a user starts to make a tap motion but stops it by lifting their finger off the widget before releasing it. It has nothing to do with stopping a tap by tapping again specifically. onHover: When the cursor touches the borders of the widget, this is triggered. Once the pointer leaves the widget’s borders, the onHover property won’t be invoked again until it returns. onFocusChange: When the attention of the InkWell widget shifts, the onFocusChange attribute is activated. This might occur if the user presses the widget if the widget receives programmatic focus, or if another widget catches the user’s attention. Whether the widget has gained focus (true) or lost focus (false) is indicated by a boolean value given to the callback. When the focus of the Inkwell widget changes, you can use the onFocusChange property to take any action you desire. For instance, you may launch a new screen, alter the widget’s color, or reveal or conceal a keyboard. How Do You Remove Ripple Effect From InkWell Flutter? You can remove the Inkwell ripple effect by turning the value of highlightColor and splashColor to Colors.transparent. Material( color: Colors.yellow, child: InkWell( onTap: () { print(‘InkWell tapped!’); }, highlightColor: Colors.transparent, splashColor: Colors.transparent, child: const SizedBox( width: 100.0, height: 100.0, child: Center(child: Text(‘Tap Me’)), ), ), ), This is how the code appears visually: Flutter Gesturedetector vs. Inkwell Though both work on touch interaction, the output is different for each. Where the Flutter GestureDetector takes in the touch interaction with the application, Inkwell Flutter puts it visually onto the screen by displaying a ripple effect. A GestureDetector Flutter is a non-visual widget, whereas InkWell displays what a GestureDetector does backstage on the screen. Besides this,

Read More »

Flutter Google Maps Marker: An In-Depth Tutorial

How we connect with and navigate the world has radically changed. Thanks to Google Maps, a comprehensive and widely used tool. On the other hand, Flutter has a considerable increase in popularity among developers due to its native performance, capacity for hot-reloading, and adaptable widgets. Have you ever imagined how we can include this robust architecture in Google Maps? Welcome to this comprehensive guide on utilizing the Flutter Google Maps Marker. In this post, we will delve into how to create interactive maps in your app using Flutter Google Maps. Can You Use Google Maps In Flutter? Yes, you can incorporate Google Maps into a Flutter application. A plugin to display Google Maps in your application is available, thanks to the google_maps_flutter plugin. First of all, you need to enable Maps SDK for Android and Maps SDK for iOS from Google Cloud Console; then, you need a Google Cloud Platform API key to integrate Google Maps into your Flutter project. You can obtain this key by starting a new project in the Google Cloud Platform dashboard and turning on the Google Maps API for that project. Google Map Flutter Tutorial To make integrating Google Maps into a Flutter application easier, Flutter Maps provides a Google Maps Flutter plugin. By enabling you to integrate and alter Google Maps views straight from your Flutter code, this plugin offers a quick and smooth method of integrating Google Maps into your projects. You wouldn’t believe how easy it is to integrate Google Maps into a Flutter project. Following are the steps to integrate google maps into Flutter Project: Before you do anything further, ensure your environment is configured correctly and that you have loaded the most recent Flutter SDK version. Now you need to add the google_maps_flutter plugin in your pubspec.yaml file, after which you should run the flutter pub get command to fetch the plugin. Go to the Google Cloud Platform Console website (console.cloud.google.com) and sign in to your Google account. Following are three illustrations to your command: Click on the “Select a project” dropdown at the top of the page. A dialog will pop up, and choose “New Project” from the top right side of the dialog. Provide the required information, such as the project name, organization, and billing account. Once your project is created, you’ll be redirected to the project’s dashboard. In the search bar at the top of the page, type “Google Maps SDK” and select the appropriate result. Below is how your screen will appear: On the SDK’s information page, click the “Enable” button to enable the Google Maps SDK for your project. This is what your screen looks like: After enabling the SDK, navigate to the “Credentials” section of the Google Cloud Platform Console. You can find it by clicking on the menu icon in the top-left corner and selecting “APIs & Services” > “Credentials” from the sidebar. Below is the visual representation to your command: In the Credentials section, click the “Create Credentials” button and choose “API Key” from the dropdown menu. This is how it appears:  A dialog box will appear with your newly created API key. Copy the API key and securely store it, as you’ll need it to interact with Google Maps services in your Flutter project. This is how your screen will look like after following the step: The final step is to Implement Map View. Following setup, we begin developing our Flutter app. Create a Dart file, import the google_maps_flutter package, and configure a GoogleMap widget. What Are the Features of Google Maps in Flutter? Flutter Google Maps offers a wide range of functions to provide an interactive, personalized map experience in your app. You may deliver a user experience that stands out by being aware of and utilizing these features effectively. Google Maps in Flutter is a powerful tool beyond just displaying maps. Some key features include: Markers: Markers indicate/highlight specific locations. Custom map styling: With the ability to customize your map’s style, you can match the map design according to the theme of your application. Camera Control: Google Maps Flutter offers extensive camera control options. The camera can be moved programmatically to any location or flutter google maps’ current location, zoomed in or out, and even tilted for a more 3D perspective. User Interaction: You can capture user interaction with the map to create a more engaging experience, such as taps, drags, zoom, etc. Polylines: Google Maps Flutter Polyline and  Polygon helps to highlight routes or areas on your map. Flutter Google Maps Calculate Distance You can use the package to calculate the distance between two points using Google Maps in a Flutter application. This package provides a LatLng class to represent latitude and longitude coordinates. To calculate the distance, you can utilize the Haversine formula or the SphericalUtil class from the google_maps_flutter package offers utility methods for performing geometric calculations on the Earth’s surface. Bypassing the coordinates of the two points to the appropriate method, you can obtain the distance between them in meters or kilometers, enabling you to incorporate distance calculations into your Flutter Google Maps application. How to Add Custom Marker in Google Map Flutter Use markers to make your map more dynamic and user-friendly. These marks may represent tourist attractions, user sites, or other significant locations. The following is how to add unique markers: Making a BitmapDescriptor is necessary to create the marker’s icon. Either utilize the built-in markers or generate a custom BitmapDescriptor from a picture. Once you have a BitmapDescriptor, you can construct a Marker object. The Marker requires a LatLng for the position,  markerId (unique identification), and a BitmapDescriptor for the icon. Create the marker and add it to the map: The markers property of the GoogleMap widget is used to add the marker you just created to your map. Dynamically Add Markers to Google Maps Flutter Let’s assume you have a restaurant called “The OpenAI Diner.” Here’s how you’d add a marker for it on the map: Fetch Data: Request the

Read More »

Unleashing Flutter Riverpod: State Management Mastery

Riverpod Flutter has revolutionized how we handle state in our applications and has swept the Flutter development community. Using Flutter Riverpod, a potent state management tool, managing and sharing state in Flutter applications is more accessible. If you’ve ever struggled with intricate state management systems or felt lost in boilerplate code, feel free! The Flutter Riverpod is here to transform your app development process. In this post, we will examine Riverpod in-depth and see how its streamlined state management features enhance your Flutter apps. What Is Riverpod In Flutter? For Flutter apps, Riverpod is a state management library. It is based on the Provider package and provides an alternate method for handling state in Flutter apps. You can specify providers using riverpod flutter, which serves as the state’s source of truth. Fine-grained control over how the state is accessed and exchanged is possible with the help of these providers, which can be scoped to specific widget subtrees or inherited throughout the widget tree. Utilizing Riverpod allows developers to separate UI elements from business logic, handle state changes efficiently, and reduce boilerplate code. Riverpod Providers Provider makes the core of Riverpod’s state management approach. They serve as a source of truth for the state of your app and let you read and update that state from different areas of your Flutter application. Riverpod Flutter supports a variety of providers, each of which serves a particular function. Provider This is the most basic provider. It takes value and exposes it. This value cannot change over time, and if you need a mutable state, you should use other types of providers. FutureProvider This is a provider that works with Futures. It gives you async loading, error handling, and out-of-the-box caching. ChangeNotifierProvider Creates a ChangeNotifier and exposes its current state. Combined with ChangeNotifier, ChangeNotifierProvider can manipulate advanced states that would otherwise be difficult to represent with more straightforward providers such as Provider or FutureProvider. StateNotifierProvider Similar to ChangeNotifierProvider, but works with StateNotifiers. A StateNotifier is a way to encapsulate a mutable state with specific methods for modifying that state. StreamProvider Regarding Streams instead of Futures, StreamProvider is comparable to FutureProvider. StreamProvider is typically utilized:  For listening to Firebase or web-sockets  rebuilding a different provider within seconds. Some people might believe that utilizing StreamProvider has little utility because Streams, by their very nature, give a mechanism to listen to updates. The value of the StreamBuilder provided by Flutter could be better. Listening to a stream would be as effective using Flutter’s StreamBuilder, but this needs to be corrected. Using StreamProvider over StreamBuilder has numerous benefits: It lets other services hear the streamed data using a feature called ref.watch. It takes care of loading and error situations with the help of a tool named AsyncValue. It eliminates the need to distinguish between two types of data streams: broadcast and regular. It holds onto the most recent piece of data from the stream. So even if a listener joins late, they still get the latest information. It makes testing easier. You can mimic the data stream during tests by changing the StreamProvider. Flutter Riverpod Example Here’s a simple example of how you can use Riverpod for state management in a Flutter app: below is the mentioned flutter riverpod login example showcases a basic counter app that utilizes Riverpod for state management, providing a reactive UI that updates in response to changes in the counter value. Firstly, we define a CounterNotifier using StateProvider instead of Provider. This allows us to directly access and modify the state using the .state property of the provider. Then we define counterNotifierProvider using StateNotifierProvider, which returns an instance of CounterNotifier. We wrap our MaterialApp with ProviderScope to use Riverpod’s provider The HomePage is now a ConsumerWidget, which automatically rebuilds itself whenever the value of the counter changes. Inside the build method, we use the ref.watch function provided by WidgetRef to access the counter value from the provider. This ensures that the UI stays updated with the current counter value. When the floating action button is pressed, we pass the notifier property of counterNotifierProvider to the ref.read function and call the increment function of the CounterNotifier. import ‘package:flutter/material.dart’; import ‘package:flutter_riverpod/flutter_riverpod.dart’; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const ProviderScope( child: MaterialApp(home: HomePage()), ); } } final counterNotifierProvider = StateNotifierProvider((_) => CounterNotifier()); class CounterNotifier extends StateNotifier<int> { CounterNotifier() : super(0); void increment() => state++; } class HomePage extends ConsumerWidget { const HomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { final count = ref.watch(counterNotifierProvider); return Scaffold( appBar: AppBar(title: const Text(‘Riverpod’), centerTitle: true), body: Center(child: Text(‘Count => $count’)), floatingActionButton: FloatingActionButton( onPressed: ref.read(counterNotifierProvider.notifier).increment, child: const Icon(Icons.add), ), ); } }   This is how the upper mentioned examples turn out to be: Why Choose Riverpod For State Management? Several compelling factors are responsible for Riverpod’s increasing popularity. First, it stands out because of its simplicity. Even developers unfamiliar with Flutter or state management principles can use Flutter Riverpod API because it is made to be simple to learn and utilize. In addition, flutter riverpod consumer has exceptional scalability, enabling developers to effectively manage the state in small and complex applications. The decoupling of UI and business logic by Riverpod encourages a separation of responsibilities, which makes codebases simpler to maintain and test. What Is The Difference Between Riverpod And StackedFlutter? The critical difference between Riverpod and Stacked is the following: State Management Approach Flutter_Riverpod, a state management library, aims to offer a simple and scalable solution for managing the state in Flutter projects. It is based on the Provider package and encourages a compositional and hierarchical approach to state management. While on the other hand, stacked Flutter is a pattern for architectural design that goes beyond state management. It uses reactive view models to handle the state using the Flutter Riverpod MVVM architecture. Scope and Flexibility To provide users with fine-grained control over where and how the state is accessible and shared

Read More »

Mastering Dismissible in Flutter: Unlock the Power of Swipe Gestures

Have you ever used a smartphone and could swipe away or dismiss certain items on the screen? In Flutter, a powerful Dismissible widget lets you do just that in your app. It’s like giving your users the superpower of swiping away items with a simple touch! With much applause, people still need clarification on what precisely dismissible features are offered in widgets. We hope this article will assist you in the best possible way. What is Dismissible in the Flutter App? In simple terms, dismissible is the widget in Flutter that enables you to add swipe gestures within your application. It’s commonly used to build features like swiping to delete or archive items, similar to what you see in email or to-do list apps. It allows the user to detect swipe gestures and perform actions accordingly. When a user swipes an item, the dismissible widget flutter takes care of the animation for you. It smoothly slides the item off the screen, giving users satisfying visual feedback. You can customize the animation by providing optional parameters like background, secondaryBackground, and direction. How Does Dismissible Work? To use Dismissible, you wrap it around the widget representing each item in your list. This can be any Flutter widget, such as ListTile, Card, or Container. Dismissible takes a few required parameters, including key and child. Key: Helps Flutter keep track of each item in the list uniquely. Child: Represents the widget that users will swipe to dismiss. onDismissed: Defines what happens when an item is swiped away. ( and it is an optional parameter ) Customizing Dismissible In Flutter Customizing Background: When using Dismissible in Flutter, you can customize the background behind the item as it’s being swiped from Left to Right. This background widget typically indicates that the item will be deleted or archived. How to customize the background dismiss in Flutter?  To customize the background, you can utilize the background parameter of the Dismissible widget. This parameter accepts a widget of your choice, allowing you to design and style it to fit your app’s theme. You can use containers, images, icons, or any other widget to create the desired visual effect. Customizing Secondary Background In addition to the main background, Dismissible also allows you to specify a secondary background. This background appears when swiping the item in the Right to Left direction. It’s helpful to provide different actions based on the swipe direction. How to specify secondary background? To customize the secondary background, you can use the secondaryBackground parameter of the Dismissible widget. Like the background, this parameter accepts a widget that you can design and style to your liking. A code example to show how you can customize background and secondaryBackground Dismissible( key: UniqueKey(), background: Container( width: double.infinity, color: Colors.red, height: 100, ), secondaryBackground: Container( width: double.infinity, color: Colors.yellow, height: 100, ), child: const ListTile( title: Text(‘Dismissible’), trailing: Icon(Icons.add), ), ) Here is the visual representation of  how the code works: Customizing Direction By default, Dismissible in Flutter supports both left-to-right and right-to-left swipes. However, there may be cases where you want to limit the swipe direction to a specific orientation. How to limit swipe direction to a specific direction in Flutter? To limit the swipe direction, you can use the direction parameter of the Dismissible widget. This parameter takes a DismissDirection enum value, which allows you to specify the allowed swipe direction. Utilizing these customization options allows you to create visually appealing and interactive swipe actions in your Flutter app. Customizing the background and secondaryBackground allows you to match your app’s design and provides clear indications of the actions users can take. Also Read –  Flutter gesturedetector mastering gestures guide How to disable swiping in the dismissible widget in Flutter? To disable swiping in a Dismissible widget in Flutter, set the direction parameter to DismissDirection.none. With DismissDirection.none, the Dismissible widget won’t respond to swipe gestures, effectively disabling swiping in both left-to-right and right-to-left directions. To disable swiping from right to left (start to end): Dismissible( // other parameters… direction: DismissDirection.endToStart, // Disable swiping from right to left // child and onDismissed… ) To disable swiping from left to right (end to start): Dismissible( // other parameters… direction: DismissDirection.startToEnd, // Disable swiping from left to right // child and onDismissed… ) 5 Advantages of Dismissible Widget in Flutter Prevent accidental dismissals: A confirmDismiss parameter in Dismissible allows you to ask the user for approval before completing the dismissal action, which helps to avoid unintentional dismissals. This helps add an extra degree of security for users and helps prevent unintentional dismissals. Flexibility and Versatility: Dismissible can be used with various widgets, such as ListTile, Card, or Container, allowing you to incorporate swipe-to-dismiss functionality. Whether it’s a list of messages, tasks, or any other type of item, Dismissible can adapt to different scenarios and use cases. Enhanced User Experience: Dismissible allows users to interact with your app through intuitive swipe gestures, making the user experience more engaging and interactive. Simplified Implementation: Dismissible simplifies adding swipe gestures to your app. With just a few parameters and callbacks, you can enable swipe-to-dismiss functionality for individual list items or widgets without implementing complex gesture recognition logic from scratch. Animation Support: Dismissible includes built-in animations that smoothly slide the item off the screen when dismissed. Conclusion Using the Dismissible widget in Flutter enhances the user experience, simplifies implementation, provides customizable swipe actions, supports animations, offers flexibility, and promotes code reusability. It empowers developers to create user-friendly and interactive apps with swipe-to-dismiss functionality. If you are a beginner and want a more intuitive app experience, you can hire Flutter developers to get an expert at your desk.  

Read More »

InheritedWidget in Flutter: Building Robust and Dynamic Flutter UIs

Among the various state management solutions, one that often goes underappreciated is the Inherited Widget. It’s a robust, efficient, and flexible technique, largely built into the Flutter framework. InheritedWidget in Flutter is a special widget designed to propagate information down the widget tree efficiently. Besides provider and flutter riverport, getting a deep understanding of what an inherited widget is and how to use the inherited widget in Flutter is very crucial at the Developer’s end to create complex UIs. Let’s get started with it. What is an Inherited Widget in Flutter? Inherited Widgets are a vital component of Flutter’s Widget system, providing a powerful and efficient way of passing data down the tree. The fundamental idea behind InheritedWidget is to provide a way to access data from a parent widget to one or more descendant widgets without passing the state down through constructor parameters. It leverage dart’s object-oriented capabilities and Flutter’s reactive UI updates to create a flexible, intuitive, and performant state management system. How to Use Inherited Widget Flutter Example Inherited Widgets create a data layer their descendants can access via their context. The data isn’t stored in the Inherited Widget itself but in a separate model class that the Inherited Widget takes as a parameter. First, we’ll create our InheritedWidget: ThemeColor is an InheritedWidget with a color property in this snippet. class ThemeColor extends InheritedWidget { final Color color; const ThemeColor({Key? key, required this.color, required Widget child}) : super(child: child, key: key); @override bool updateShouldNotify(ThemeColor oldWidget) { return color != oldWidget.color; } static ThemeColor? of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<ThemeColor>(); } } Next, we’ll create the widget: that uses this ThemeColor: In this Box widget, we are accessing the color from our ThemeColor InheritedWidget and applying it to the Container. class Box extends StatelessWidget { const Box({super.key}); @override Widget build(BuildContext context) { final color = ThemeColor.of(context)?.color ?? Colors.black; return Container( width: 100, height: 100, color: color, ); } } Now, we use these widgets in our main application: In the below snippet, we’re wrapping our Scaffold with the ThemeColor InheritedWidget and setting the color to Colors.red. Then, within the Box widget, we access the ThemeColor InheritedWidget and apply the color to our box. void main() => runApp(MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: ThemeColor( color: Colors.red, child: Scaffold( appBar: AppBar(), body: const Center(child: Box()), ), ), ); } } This is a simple example of how to use InheritedWidget to pass down data (in this case, a color) to descendant widgets in Flutter. Inherited Widget Vs. Provider Features  Inherited Widget Flutter  Complexity Complex Simple State Managment Propagates Data Handles State changes and listener Notifications Multi Provider Capability No Built-in. Have to Set it Manually Has ‘multi provider’ widget Lifecycle Management Manual Built-in Performance Good Optimized What is the Difference Between InheritedWidget and Inherited Model? InheritedWidget and InheritedModel are Flutter classes that propagate information down the widget tree. However, they have a key difference in determining when to notify dependents of changes. When an InheritedWidget changes, based on its updateShouldNotify method, it will notify all dependent widgets in the tree, and those widgets will rebuild. Whereas the InheritedModel will only notify those dependent widgets related to the changed aspects, leading to potentially fewer widget rebuilds. Flutter InheritedWidget with ChangeNotifier ChangeNotifier is a class provided by Flutter that can be used with InheritedWidget to manage the state. It provides a way to listen for changes to a model and allows all listeners (typically widgets) to update their state accordingly. An InheritedWidget provides a way to share data across the widget tree, and a ChangeNotifier provides a way to listen for changes to that data. They can help efficiently manage and respond to changes in your application’s state when used together. 👉 Inkwell flutter widget Example: How to Use ChangeNotifier with InheritedWidget Let’s define a simple ChangeNotifier: In the Counter class mentioned below, notifyListeners() is called whenever the count changes. This will trigger any listeners of this ChangeNotifier to rebuild. class Counter with ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } } Now, let’s create our InheritedNotifier: Here, InheritedNotifier is a specialized kind of InheritedWidget that works well with ChangeNotifier. It automatically calls updateShouldNotify when the ChangeNotifier calls notifyListeners, causing the widgets listening to this InheritedNotifier to rebuild. class CounterInheritedNotifier extends InheritedNotifier<Counter> { const CounterInheritedNotifier({ super.key, required Widget child, required Counter notifier, }) : super(child: child, notifier: notifier); static CounterInheritedNotifier? of(BuildContext context) { return context .dependOnInheritedWidgetOfExactType<CounterInheritedNotifier>(); } } Finally, you could use your CounterInheritedNotifier in your widget tree like this: Counter _counter = Counter(); CounterInheritedNotifier( notifier: _counter, child: YourWidgetTree(), ); Then in any descendant widget, you could access the counter and increment it like this: final counterInheritedNotifier = CounterInheritedNotifier.of(context); final counter = counterInheritedNotifier?.notifier; final count = counter?.count ?? 0; ElevatedButton( onPressed: counter?.increment, child: const Text(‘Increment’), ) In this setup, when you call the counter.increment, it updates the count and then calls notifyListeners, triggering updateShouldNotify in the InheritedNotifier, causing all widgets to listen to the InheritedNotifier to rebuild. Here is a visual representation of the above-mentioned code: 3 Key Features of Flutter Inherited Widget You might be aware of the common technicalities; the following are some ways where you could increase the efficiency of the inherited widget Automatic Rebuilds If the inherited data changes, InheritedWidget will immediately rebuild dependent widgets. Because of this, updating the UI in response to changes in the shared state is simple and doesn’t need manually handle state dependencies and trigger updates. The UI will accurately reflect the most recent state of the application since the widgets that rely on the inherited data will be effectively regenerated. Ancestor Access It is another hidden gem that can aid with more advanced use cases. Widgets can access their ancestor Inherited Widgets to retrieve data. This feature can be handy when dealing with nested data models or scoped themes. Querying Multiple Inherited Widgets While Inherited Widgets are great for

Read More »