<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Azhar Ali on Medium]]></title>
        <description><![CDATA[Stories by Azhar Ali on Medium]]></description>
        <link>https://medium.com/@azharbinanwar?source=rss-6e819b7bb292------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8-Az3EM_JrkHshkHZC53IA.png</url>
            <title>Stories by Azhar Ali on Medium</title>
            <link>https://medium.com/@azharbinanwar?source=rss-6e819b7bb292------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:13:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@azharbinanwar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Abstract Classes as Interfaces in Dart: Building Flexible Flutter Applications]]></title>
            <link>https://medium.com/@azharbinanwar/abstract-classes-as-interfaces-in-dart-building-flexible-flutter-applications-2f9593b31a63?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f9593b31a63</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[flutter-best-practice]]></category>
            <category><![CDATA[abstract-class]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 11:36:08 GMT</pubDate>
            <atom:updated>2025-03-20T11:36:08.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5w0IQ2QlR2fvEir3VvVJw.png" /></figure><h3>Introduction</h3><p>In Dart and Flutter development, programming with abstract classes creates a powerful design pattern that enhances maintainability, testability, and flexibility. Dart uses abstract classes as a way to define contracts that concrete classes can implement. This approach is particularly valuable in Flutter where we often need different implementations for various platforms, testing scenarios, and feature variations.</p><h3>Understanding Abstract Classes in Dart</h3><p>In Dart, we create interface-like behavior using abstract classes with the implements keyword:</p><pre>abstract class AuthenticationService {<br>  Future&lt;User?&gt; signIn(String email, String password);<br>  Future&lt;void&gt; signOut();<br>  Future&lt;User?&gt; getCurrentUser();<br>}</pre><p>This abstract class defines a contract that any authentication implementation must fulfill. Multiple concrete classes can implement this abstract class, allowing for flexibility and interchangeability.</p><h3>Authentication Service Example</h3><h4>The Abstract Contract</h4><pre>abstract class AuthenticationService {<br>  Future&lt;User?&gt; signIn(String email, String password);<br>  Future&lt;void&gt; signOut();<br>  Future&lt;User?&gt; getCurrentUser();<br>}</pre><h4>Implementations</h4><p><strong>Firebase Implementation</strong></p><pre>class FirebaseAuthService implements AuthenticationService {<br>  final FirebaseAuth _auth = FirebaseAuth.instance;<br><br>  @override<br>  Future&lt;User?&gt; signIn(String email, String password) async {<br>    final result = await _auth.signInWithEmailAndPassword(<br>      email: email,<br>      password: password,<br>    );<br>    return result.user;<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; signOut() =&gt; _auth.signOut();<br>  <br>  @override<br>  Future&lt;User?&gt; getCurrentUser() async =&gt; _auth.currentUser;<br>}</pre><p><strong>REST API Implementation</strong></p><pre>class RestApiAuthService implements AuthenticationService {<br>  final HttpClient _apiClient;<br>  <br>  RestApiAuthService(this._apiClient);<br><br>  @override<br>  Future&lt;User?&gt; signIn(String email, String password) async {<br>    final response = await _apiClient.post(<br>      &#39;/auth/login&#39;,<br>      data: {&#39;email&#39;: email, &#39;password&#39;: password},<br>    );<br>    <br>    if (response.statusCode == 200) {<br>      return User(<br>        id: response.data[&#39;userId&#39;],<br>        email: email,<br>      );<br>    }<br>    return null;<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; signOut() async {<br>    await _apiClient.post(&#39;/auth/logout&#39;);<br>  }<br>  <br>  @override<br>  Future&lt;User?&gt; getCurrentUser() async {<br>    final response = await _apiClient.get(&#39;/auth/user&#39;);<br>    if (response.statusCode == 200) {<br>      return User(<br>        id: response.data[&#39;userId&#39;],<br>        email: response.data[&#39;email&#39;],<br>      );<br>    }<br>    return null;<br>  }<br>}</pre><h3>Usage with State Management</h3><pre>class AuthenticationProvider extends ChangeNotifier {<br>  final AuthenticationService _authService;<br>  <br>  AuthenticationProvider(this._authService);<br>  <br>  Future&lt;void&gt; signIn(String email, String password) async {<br>    final user = await _authService.signIn(email, password);<br>    // Handle authentication state<br>    notifyListeners();<br>  }<br>}</pre><pre>// Usage in widget remains unchanged regardless of the implementation<br>class LoginScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Consumer&lt;AuthenticationProvider&gt;(<br>      builder: (context, auth, _) =&gt; ElevatedButton(<br>        onPressed: () =&gt; auth.signIn(&#39;email&#39;, &#39;password&#39;),<br>        child: Text(&#39;Login&#39;),<br>      ),<br>    );<br>  }<br>}</pre><h3>Dependency Injection Setup</h3><pre>// Register with GetIt<br>getIt.registerSingleton&lt;AuthenticationService&gt;(FirebaseAuthService());<br><br>// Easily switch to a different implementation<br>// getIt.registerSingleton&lt;AuthenticationService&gt;(RestApiAuthService(apiClient));</pre><h3>Testing with Mock Implementation</h3><pre>class MockAuthenticationService extends Mock implements AuthenticationService {}<br><br><br>void main() {<br>  late MockAuthenticationService mockAuth;<br>  late AuthenticationProvider authProvider;<br>  <br>  setUp(() {<br>    mockAuth = MockAuthenticationService();<br>    authProvider = AuthenticationProvider(mockAuth);<br>  });<br>  <br>  test(&#39;updates state when authentication succeeds&#39;, () async {<br>    when(mockAuth.signIn(any, any))<br>        .thenAnswer((_) async =&gt; MockUser());<br>    await authProvider.signIn(&#39;email&#39;, &#39;password&#39;);<br>    // Test assertions<br>  });<br>}</pre><h3>API Service Example</h3><h4>The Abstract Contract</h4><pre>abstract class ApiService {<br>  Future&lt;T&gt; get&lt;T&gt;(String endpoint);<br>  Future&lt;T&gt; post&lt;T&gt;(String endpoint, Map&lt;String, dynamic&gt; data);<br>  Future&lt;T&gt; put&lt;T&gt;(String endpoint, Map&lt;String, dynamic&gt; data);<br>  Future&lt;void&gt; delete(String endpoint);<br>}</pre><h4>Implementations</h4><p><strong>Dio Implementation</strong></p><pre>class DioApiService implements ApiService {<br>  final Dio _dio;<br>  DioApiService(this._dio);<br>  <br>  @override<br>  Future&lt;T&gt; get&lt;T&gt;(String endpoint) async {<br>    final response = await _dio.get(endpoint);<br>    return response.data as T;<br>  }<br>  <br>  @override<br>  Future&lt;T&gt; post&lt;T&gt;(String endpoint, Map&lt;String, dynamic&gt; data) async {<br>    final response = await _dio.post(endpoint, data: data);<br>    return response.data as T;<br>  }<br>  <br>  @override<br>  Future&lt;T&gt; put&lt;T&gt;(String endpoint, Map&lt;String, dynamic&gt; data) async {<br>    final response = await _dio.put(endpoint, data: data);<br>    return response.data as T;<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; delete(String endpoint) async {<br>    await _dio.delete(endpoint);<br>  }<br>}</pre><p><strong>Mock Implementation</strong></p><pre>class MockApiService implements ApiService {<br>  final Map&lt;String, dynamic&gt; _mockData;<br>  MockApiService(this._mockData);<br>  <br>  @override<br>  Future&lt;T&gt; get&lt;T&gt;(String endpoint) async {<br>    return _mockData[endpoint] as T;<br>  }<br>  <br>  @override<br>  Future&lt;T&gt; post&lt;T&gt;(String endpoint, Map&lt;String, dynamic&gt; data) async {<br>    _mockData[endpoint] = data;<br>    return data as T;<br>  }<br>  <br>  @override<br>  Future&lt;T&gt; put&lt;T&gt;(String endpoint, Map&lt;String, dynamic&gt; data) async {<br>    _mockData[endpoint] = data;<br>    return data as T;<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; delete(String endpoint) async {<br>    _mockData.remove(endpoint);<br>  }<br>}</pre><h3>Usage in a Repository</h3><pre>class ProductRepository {<br>  final ApiService _apiService;<br>  <br>  ProductRepository(this._apiService);<br>  <br>  Future&lt;List&lt;Product&gt;&gt; getProducts() async {<br>    final data = await _apiService.get&lt;List&lt;dynamic&gt;&gt;(&#39;/products&#39;);<br>    return data.map((json) =&gt; Product.fromJson(json)).toList();<br>  }<br>  <br>  Future&lt;Product&gt; createProduct(Product product) async {<br>    final data = await _apiService.post&lt;Map&lt;String, dynamic&gt;&gt;(<br>      &#39;/products&#39;, <br>      product.toJson()<br>    );<br>    return Product.fromJson(data);<br>  }<br>}</pre><h3>Dependency Injection Setup</h3><pre>// Production environment<br>getIt.registerSingleton&lt;ApiService&gt;(DioApiService(Dio()));<br><br>// Testing or development environment<br>if (kDebugMode) {<br>  getIt.registerSingleton&lt;ApiService&gt;(MockApiService(mockData));<br>}</pre><h3>Storage Service Example</h3><h4>The Abstract Contract</h4><pre>abstract class StorageService {<br>  Future&lt;void&gt; saveString(String key, String value);<br>  Future&lt;String?&gt; getString(String key);<br>  Future&lt;void&gt; saveBool(String key, bool value);<br>  Future&lt;bool?&gt; getBool(String key);<br>  Future&lt;void&gt; remove(String key);<br>  Future&lt;void&gt; clear();<br>}</pre><h4>Implementations</h4><p>SharedPreferences Implementation</p><pre>class SharedPreferencesStorage implements StorageService {<br>  final SharedPreferences _prefs;<br>  <br>  SharedPreferencesStorage(this._prefs);<br>  <br>  @override<br>  Future&lt;void&gt; saveString(String key, String value) async {<br>    await _prefs.setString(key, value);<br>  }<br>  <br>  @override<br>  Future&lt;String?&gt; getString(String key) async {<br>    return _prefs.getString(key);<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; saveBool(String key, bool value) async {<br>    await _prefs.setBool(key, value);<br>  }<br>  <br>  @override<br>  Future&lt;bool?&gt; getBool(String key) async {<br>    return _prefs.getBool(key);<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; remove(String key) async {<br>    await _prefs.remove(key);<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; clear() async {<br>    await _prefs.clear();<br>  }<br>}</pre><h4><strong>Hive Implementation</strong></h4><pre>class HiveStorage implements StorageService {<br>  final Box _box;<br>  <br>  HiveStorage(this._box);<br>  <br>  @override<br>  Future&lt;void&gt; saveString(String key, String value) async {<br>    await _box.put(key, value);<br>  }<br>  <br>  @override<br>  Future&lt;String?&gt; getString(String key) async {<br>    return _box.get(key) as String?;<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; saveBool(String key, bool value) async {<br>    await _box.put(key, value);<br>  }<br>  <br>  @override<br>  Future&lt;bool?&gt; getBool(String key) async {<br>    return _box.get(key) as bool?;<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; remove(String key) async {<br>    await _box.delete(key);<br>  }<br>  <br>  @override<br>  Future&lt;void&gt; clear() async {<br>    await _box.clear();<br>  }<br>}</pre><h3>Usage in a Settings Manager</h3><pre>class SettingsManager {<br>  final StorageService _storage;<br>  <br>  SettingsManager(this._storage);<br>  <br>  Future&lt;void&gt; setDarkMode(bool value) async {<br>    await _storage.saveBool(&#39;darkMode&#39;, value);<br>  }<br>  <br>  Future&lt;bool&gt; getDarkMode() async {<br>    return await _storage.getBool(&#39;darkMode&#39;) ?? false;<br>  }<br>  <br>  Future&lt;void&gt; setUsername(String username) async {<br>    await _storage.saveString(&#39;username&#39;, username);<br>  }<br>  <br>  Future&lt;String?&gt; getUsername() async {<br>    return await _storage.getString(&#39;username&#39;);<br>  }<br>}</pre><h3>Dependency Injection Setup</h3><pre>// Register storage service<br>getIt.registerSingletonAsync&lt;StorageService&gt;(() async {<br>  final prefs = await SharedPreferences.getInstance();<br>  return SharedPreferencesStorage(prefs);<br>});<br><br>// Alternative storage for specific needs<br>getIt.registerFactoryAsync&lt;StorageService&gt;(() async {<br>  final box = await Hive.openBox(&#39;appData&#39;);<br>  return HiveStorage(box);<br>}, instanceName: &#39;hiveStorage&#39;);</pre><h3>Comprehensive Application Setup</h3><p>Putting it all together in an application:</p><pre>void setupDependencies() {<br>  // Register API service based on environment<br>  if (kDebugMode) {<br>    getIt.registerSingleton&lt;ApiService&gt;(MockApiService(mockData));<br>  } else {<br>    getIt.registerSingleton&lt;ApiService&gt;(DioApiService(Dio()));<br>  }<br>  <br>  // Register authentication service<br>  getIt.registerSingleton&lt;AuthenticationService&gt;(FirebaseAuthService());<br>  <br>  // Register storage service<br>  getIt.registerSingletonAsync&lt;StorageService&gt;(() async {<br>    final prefs = await SharedPreferences.getInstance();<br>    return SharedPreferencesStorage(prefs);<br>  });<br>  <br>  // Register repositories and managers<br>  getIt.registerFactory&lt;ProductRepository&gt;(<br>    () =&gt; ProductRepository(getIt&lt;ApiService&gt;())<br>  );<br>  <br>  getIt.registerFactoryAsync&lt;SettingsManager&gt;(<br>    () async =&gt; SettingsManager(await getIt.getAsync&lt;StorageService&gt;())<br>  );<br>}</pre><pre>// Application entry point<br>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await setupDependencies();<br>  runApp(MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MultiProvider(<br>      providers: [<br>        ChangeNotifierProvider(<br>          create: (_) =&gt; AuthenticationProvider(<br>            getIt&lt;AuthenticationService&gt;()<br>          ),<br>        ),<br>        // Other providers...<br>      ],<br>      child: MaterialApp(<br>        // App configuration<br>      ),<br>    );<br>  }<br>}</pre><h3>Best Practices for Dart’s Interface Pattern</h3><ol><li><strong>Define Focused Contracts</strong>: Keep abstract classes focused on a single responsibility</li><li><strong>Consistent Error Handling</strong>: Implement consistent error handling across all implementations</li><li><strong>Documentation</strong>: Document the expected behavior of each method in the abstract class</li><li><strong>Default Implementations</strong>: Consider providing default implementations for common methods</li><li><strong>Naming Conventions</strong>: Use clear naming that reflects the service’s purpose</li></ol><h3>Common Use Cases</h3><ul><li><strong>Authentication Services</strong>: Different auth providers (Firebase, Custom, Mock)</li><li><strong>API Clients</strong>: Different HTTP clients or mock APIs for testing (Dio, Http, MockClient)</li><li><strong>Storage Services</strong>: Different storage implementations (SharedPreferences, Hive, SQLite)</li><li><strong>Analytics Services</strong>: Different analytics providers (Firebase Analytics, Mixpanel, Amplitude)</li><li><strong>Platform Services</strong>: Different implementations for mobile, web, and desktop (iOS, Android, Web)</li></ul><h3>Conclusion</h3><p>Dart’s interface pattern through abstract classes provides:</p><ul><li>Clean separation of concerns</li><li>Easy testing with mock implementations</li><li>Flexible dependency injection</li><li>Maintainable and scalable code structure</li></ul><p>By leveraging this pattern in Flutter applications, developers can create more adaptable, testable code that can evolve with changing requirements while maintaining a clean architecture.</p><p>Happy Coding 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f9593b31a63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comprehensive Guide to Adding Packages in Flutter]]></title>
            <link>https://medium.com/@azharbinanwar/comprehensive-guide-to-adding-packages-in-flutter-9d860beca9a6?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d860beca9a6</guid>
            <category><![CDATA[add-packages-flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[best-flutter-packages]]></category>
            <category><![CDATA[flutter-dependencies]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 17:51:51 GMT</pubDate>
            <atom:updated>2025-02-18T03:57:24.929Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92wi8BIvmKxcb8ZYuqsV5g.png" /></figure><p>Flutter packages are a fundamental part of Flutter development, allowing developers to extend their applications with additional functionality without reinventing the wheel. This guide covers all the methods for adding packages to your Flutter projects.</p><h3>1. Using pub.dev and pubspec.yaml (Most Common Method)</h3><h4>Manual Addition</h4><p>The most straightforward way to add packages is by manually editing your pubspec.yaml file:</p><ol><li>Open your project’s pubspec.yaml file</li><li>Under dependencies:, add the package with its version:</li></ol><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br><br>  package_name: ^version_number</pre><ol><li>Run flutter pub get in your terminal</li><li>Import the package in your Dart files:</li></ol><pre>import &#39;package:package_name/package_name.dart&#39;;</pre><h4>Using Flutter CLI</h4><p>You can add packages directly through the command line:</p><pre>flutter pub add package_name</pre><p>This command automatically:</p><ul><li>Adds the package to your pubspec.yaml</li></ul><pre>Runs flutter pub get</pre><ul><li>Updates your pubspec.lock file</li></ul><h3>2. Git Dependencies</h3><p>For packages hosted on Git repositories, you can specify the source directly in your pubspec.yaml:</p><pre>dependencies:<br>  package_name:<br>    git:<br>      url: https://github.com/username/repository.git<br>      ref: branch_name  # Optional: specify branch, tag, or commit</pre><p>In your pubspec.yaml, you can reference a Git repository using SSH like this:</p><pre>dependencies:<br>  my_private_package:<br>    git:<br>      url: git@github.com:username/repo.git<br>      ref: main  # or specific branch/tag/commit</pre><h4>For BitBucket:</h4><pre>dependencies:<br>  my_private_package:<br>    git:<br>      url: git@bitbucket.org:username/repo.git</pre><h4>For Azure DevOps:</h4><pre>dependencies:<br>  my_private_package:<br>    git:<br>      url: git@ssh.dev.azure.com:v3/organization/project/repository</pre><h4>Git Dependency Variations:</h4><ul><li><strong>Specific commit:</strong></li></ul><pre>dependencies:<br>  package_name:<br>    git:<br>      url: https://github.com/username/repository.git<br>      ref: commit_hash</pre><ul><li><strong>Specific tag:</strong></li></ul><pre>dependencies:<br>  package_name:<br>    git:<br>      url: https://github.com/username/repository.git<br>      ref: v1.0.0</pre><h3>3. Path Dependencies (Local Packages)</h3><p>For local package development or when working with packages not yet published:</p><pre>dependencies:<br>  package_name:<br>    path: ../local_package_path</pre><h3>4. Hosted Packages (Custom Package Repository)</h3><p>For organizations using private package repositories:</p><pre>dependencies:<br>  package_name:<br>    hosted:<br>      name: package_name<br>      url: https://your-package-repository.com<br>    version: ^1.0.0</pre><h3>5. SDK Dependencies</h3><p>For packages that are part of the Flutter or Dart SDK:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_localizations:<br>    sdk: flutter</pre><h3>6. Development Dependencies (dev_dependencies)</h3><p>Development dependencies are packages used only during development and testing, not in the production application. They follow similar patterns to regular dependencies but are specified under dev_dependencies your pubspec.yaml.</p><h4>Basic dev_dependencies</h4><pre>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  build_runner: ^2.4.6<br>  json_serializable: ^6.7.1</pre><h4>Using Flutter CLI</h4><pre>flutter pub add dev:package_name</pre><p><strong>For example:</strong></p><pre>flutter pub add dev:build_runner<br>flutter pub add dev:mockito</pre><h4>Git-based Dev Dependencies</h4><pre>dev_dependencies:<br>  dev_package:<br>    git:<br>      url: git@github.com:username/repo.git<br>      ref: main  # optional: branch, tag, or commit</pre><h4>Local Path Dev Dependencies</h4><pre>dev_dependencies:<br>  dev_package:<br>    path: ../local_dev_package</pre><h4>Hosted Private Dev Dependencies</h4><pre>dev_dependencies:<br>  dev_package:<br>    hosted:<br>      name: dev_package<br>      url: https://your-private-repo.com<br>    version: ^1.0.0</pre><h4>Common Use Cases and Examples</h4><h4>a. Testing Packages</h4><pre>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  mockito: ^5.4.2<br>  test: ^1.24.9<br>  integration_test:<br>    sdk: flutter</pre><h4>b. Code Generation Tools</h4><pre>dev_dependencies:<br>  build_runner: ^2.4.6<br>  json_serializable: ^6.7.1<br>  freezed: ^2.4.5<br>  auto_route_generator: ^7.3.1</pre><h4>c. Static Analysis and Linting</h4><pre>dev_dependencies:<br>  flutter_lints: ^2.0.3<br>  custom_lint: ^0.5.7<br>  dart_code_metrics: ^5.7.6</pre><h3>Best Practices and Tips</h3><h4>Version Constraints</h4><ul><li>Caret syntax (^): ^1.2.3 allows all versions from 1.2.3 to 2.0.0</li></ul><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br><br>  package_name: ^1.2.3 # 1.2.3 to 2.0.0</pre><ul><li>Exact version: 1.2.3 allows only version 1.2.3</li></ul><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br><br>  package_name: 1.2.3 # Only 1.2.3</pre><ul><li>Range: &#39;&gt;=1.2.3 &lt;2.0.0&#39; allows versions within the specified range</li></ul><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br><br>  package_name: &#39;&gt;=1.2.3 &lt;2.0.0&#39; # &#39;&gt;=1.2.3 &lt;2.0.0&#39; all versions within the specified range</pre><h4>Dependency Resolution</h4><ol><li>Run flutter pub outdated to check for package updates</li><li>Use flutter pub upgrade to upgrade all packages</li><li>Use flutter pub upgrade --major-versions for major version upgrades</li></ol><h4>Security Considerations</h4><ol><li>Always verify package sources</li><li>Check package documentation for compatibility</li><li>Review package licenses</li><li>Test thoroughly after adding new packages</li></ol><h4>Performance Optimization</h4><ol><li>Remove unused packages</li><li>Keep packages updated</li><li>Consider package size and impact on app size</li><li>Use dev_dependencies for packages only needed during development</li></ol><h4>Common Issues and Solutions</h4><h4>Version Conflicts</h4><p>If you encounter version conflicts:</p><ul><li>Check your pubspec.lock file</li><li>Use flutter pub deps to view the dependency tree</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICVtJeU74LwmtFxtLEoncA.png" /></figure><ul><li>Adjust version constraints</li><li>Consider using dependency_overrides as a last resort</li></ul><h4>Package Not Found</h4><p>If packages aren’t found:</p><ol><li>Verify package name spelling</li><li>Check internet connection</li><li>Ensure pub.dev is accessible</li><li>Verify package exists for your Flutter version</li></ol><h3>Conclusion</h3><p>Understanding these different methods of adding packages to your Flutter project is crucial for efficient development. Choose the appropriate method based on your specific needs:</p><ul><li>Use pub.dev for public packages</li><li>Use Git dependencies for unreleased features</li><li>Use path dependencies for local development</li><li>Use hosted dependencies for private packages</li></ul><p>Happy Coding 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d860beca9a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter: extensions_plus Write Cleaner, More Maintainable Code]]></title>
            <link>https://medium.com/@azharbinanwar/flutter-extensions-plus-write-cleaner-more-maintainable-code-d73646406371?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73646406371</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 13:47:12 GMT</pubDate>
            <atom:updated>2025-02-15T13:55:48.729Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnhyfnNMqkFMPkiNtpaX6g.png" /></figure><p>Flutter development often involves writing repetitive boilerplate code that can make your codebase verbose and harder to maintain. This can lead to increased development time, decreased readability, and potential for errors.</p><p><strong>extensions_plus:</strong> a powerful Flutter utility package designed to streamline your development workflow. By providing a rich set of extension methods for common data types like String, BuildContext, Num, Widget, and DateTime, extensions_plus empowers you to write cleaner, more concise, and maintainable code.</p><h4>Getting Started</h4><ol><li>Add extensions_plus to your pubspec.yaml:</li></ol><pre>dependencies:<br>  extensions_plus: ^latest_version</pre><p>2. Run pub get:</p><pre>flutter pub get</pre><p>3. Import the package:</p><pre>import &#39;package:extensions_plus/extensions_plus.dart&#39;;</pre><h3>Key Features</h3><ul><li><strong>BuildContext Extensions</strong>: Simplify access to themes, navigation, and device configurations, making context-related operations more intuitive.</li><li><strong>String Extensions</strong>: Enhance text manipulation with utilities for capitalization, validation, pattern matching, and more.</li><li><strong>Numeric Extensions</strong>: Introduce mathematical and formatting utilities to handle numerical data more effectively.</li><li><strong>Collection Extensions</strong>: Provide advanced operations for Iterables, Lists, and Maps, facilitating more efficient data handling.</li><li><strong>DateTime Extensions</strong>: Improve date and time handling with added functionalities for Dart’s DateTime class.</li><li><strong>Widget Extensions</strong>: Streamline UI development with chainable methods, promoting a more declarative style.</li><li><strong>Color Extensions</strong>: Enable sophisticated color manipulation, aiding in dynamic theming and design consistency.</li></ul><h4>Simplified Navigation 🚀</h4><p>Navigation in Flutter typically requires verbose boilerplate code. Compare these approaches:</p><pre>// Traditional approach<br>Navigator.of(context).push(<br>  MaterialPageRoute(<br>    builder: (context) =&gt; HomeScreen(),<br>    fullscreenDialog: true,<br>  ),<br>);<br><br>Navigator.of(context).pushReplacement(<br>  MaterialPageRoute(<br>    builder: (context) =&gt; HomeScreen(),<br>  ),<br>);<br><br>// With extensions_plus<br>context.push(HomeScreen(), fullscreenDialog: true);<br>context.pushReplacement(HomeScreen()); </pre><p>The extension method not only reduces code length but also makes the intent clearer and more readable.</p><h4>Theme Access Made Easy 🎨</h4><p>Accessing these data in Flutter can be cumbersome. Here’s how extensions_plus simplifies it:</p><pre>// Traditional approach<br>Text(<br>  &#39;Heading&#39;, <br>  style: Theme.of(context).textTheme.headlineMedium<br>);<br>// Text color<br>Text(<br>  &#39;Heading - color&#39;, <br>  style:TextStyle(<br>    color: Theme.of(context).colorScheme.primary<br>  )<br>);<br><br>// With extensions_plus<br>Text(&#39;Heading&#39;, style: context.headlienMedium)<br>// Text Color<br>Text(<br>  &#39;Heading - color&#39;, <br>  style:TextStyle(color: context.primary)<br>);</pre><p>The extension methods provide a more fluent interface for working with these data, reducing nesting and improving readability.</p><h4>Elegant DateTime Handling 📅</h4><p>Date formatting and manipulation become much more straightforward:</p><pre><br>// Create a reusable DateTime object  <br>final date = DateTime(2025, 1, 29, 15, 45);  <br><br>// Traditional approach  <br>DateFormat(&#39;MMM dd, yyyy&#39;).format(date);  <br>// Output: &quot;Jan 29, 2025&quot;  <br>date.format(&#39;EEEE, MMMM d, yyyy h:mm a&#39;);  <br>// Output: &quot;Tuesday, January 29, 2025 3:45 PM&quot;  <br><br><br>// With extensions_plus  <br>date.format(&#39;MMM dd, yyyy&#39;);  <br>// Output: &quot;Jan 29, 2025&quot;<br>date.format(&#39;dd/MM/yyyy&#39;);  <br>// Output: &quot;29/01/2025&quot;  <br><br>// Bonus: Time ago feature  <br>date.subtract(Duration(hours: 5)).timeAgo();  <br>// Output: &quot;5 h ago&quot;</pre><h4>Streamlined Widget Styling 🎯</h4><p>Widget styling often requires nested Containers and decorations. Here’s how extensions_plus simplifies it:</p><pre>// Traditional approach<br>Container(<br>  padding: EdgeInsets.all(16),<br>  decoration: BoxDecoration(<br>    color: Colors.blue,<br>    borderRadius: BorderRadius.circular(12),<br>    boxShadow: [<br>      BoxShadow(<br>        blurRadius: 5,<br>        color: Colors.black.withOpacity(0.2)<br>      )<br>    ]<br>  ),<br>  child: Text(&#39;Hello&#39;)<br>);<br><br>// With extensions_plus<br>Text(&#39;Hello&#39;)<br>    .paddingAll(16)<br>    .background(Colors.blue)<br>    .circular(12)<br>    .elevation(5);</pre><h4>Intuitive Color Operations 🎨</h4><p>Color manipulation becomes more intuitive:</p><pre>// Traditional approach<br>Color darkerBlue = HSLColor.fromColor(Colors.blue)<br>    .withLightness(HSLColor.fromColor(Colors.blue).lightness - 0.2)<br>    .toColor();<br><br>// With extensions_plus<br>Color darkerBlue = Colors.blue.darken(0.2);</pre><h4>Collection Utilities 📝</h4><p>Working with collections becomes more expressive:</p><pre>// Traditional approach<br>final numbers = [1, 2, 3, 4, 5];<br>final evenNumbers = numbers.where((n) =&gt; n % 2 == 0).toList();<br>final total = numbers.reduce((a, b) =&gt; a + b);<br><br>// With extensions_plus<br>[1, 2, 3, 4, 5].partition((n) =&gt; n.isEven); // Output: ([2, 4], [1, 3, 5])<br>[1, 2, 3, 4, 5].sum(); // Output: 15</pre><h4>String Operations Made Simple 📝</h4><p>String manipulation becomes more intuitive:</p><pre>// Traditional approach<br>final name = &quot;john doe&quot;;<br>final capitalized = name.split(&#39; &#39;)<br>    .map((word) =&gt; word[0].toUpperCase() + word.substring(1))<br>    .join(&#39; &#39;);<br>// Result: &quot;John Doe&quot;<br><br>// With extensions_plus<br>&quot;john doe&quot;.toTitleCase();<br>// Result: &quot;John Doe&quot;<br><br>&quot;john doe&quot;.initials();<br>// Result: &quot;JD&quot;<br><br>&quot;john.doe@example.com&quot;.isEmail;<br>// Result: true</pre><h4>Responsive Design Helpers 📱</h4><p>Responsive design checks become more readable:</p><pre>// Traditional approach<br>MediaQuery.of(context).size.width &lt;= 480<br>  ? mobileLayout()<br>  : desktopLayout();<br>// Dimentions<br>var withd = MediaQuery.of(context).size.width;<br>var height = MediaQuery.of(context).size.height;<br><br>// With extensions_plus<br>context.isMobile<br>  ? mobileLayout()<br>  : desktopLayout();<br>// Dimentions<br>var withd = context.width;<br>var height = context.height;</pre><p>Here’s a fully positive and engaging version of your article:</p><h3>Boost Your Flutter Code with extensions_plus 🚀</h3><p>The extensions_plus package enhances Flutter development by making code more readable, reusable, and structured—similar to <strong>Kotlin’s Jetpack extensions</strong> and <strong>SwiftUI’s property wrappers</strong>.</p><h3>✨ Why Use extensions_plus?</h3><p>✅ <strong>Cleaner Syntax</strong> — Instead of MediaQuery.of(context).size.width &lt; 600, simply use context.isMobile.<br> ✅ <strong>Reduces Boilerplate</strong> – email.isEmail is much more intuitive than writing a regex validation every time.<br> ✅ <strong>Enhances Maintainability</strong> – Centralized extensions allow easy updates without refactoring multiple files.<br> ✅ <strong>Consistent UI Behavior</strong> – Similar to Jetpack Compose’s Modifier.fillMaxSize(), context.width makes layout handling easier.<br> ✅ <strong>Performance-Friendly</strong> – Optimized for readability without unnecessary overhead.</p><h3>🔍 Comparison with Jetpack, SwiftUI &amp; Flutter</h3><p>Modern UI frameworks follow a similar approach to improving readability and maintainability. Here’s how extensions_plus compares with Jetpack Compose and SwiftUI:</p><h4>Kotlin Jetpack Compose — Using Modifier for Layout Styling</h4><pre>@Composable<br>fun ExampleBox() {<br>    Box(<br>        modifier = Modifier<br>            .fillMaxWidth() // Similar to context.width in Flutter<br>            .padding(16.dp) // Handles spacing efficiently<br>    ) {<br>        Text(&quot;Hello, Jetpack Compose!&quot;)<br>    }<br>}</pre><h4>SwiftUI — Using View Modifiers for Adaptive UI</h4><pre>struct ExampleView: View {<br>    var body: some View {<br>        Text(&quot;Hello, SwiftUI!&quot;)<br>            .frame(maxWidth: .infinity) // Similar to context.isTablet in Flutter<br>            .padding(16) // Adds spacing without extra views<br>    }<br>}</pre><h4>Flutter with extensions_plus - Using Context Extensions for Readability</h4><pre>Widget build(BuildContext context) {<br>  return Container(<br>    width: context.width, // Cleaner than MediaQuery.of(context).size.width<br>    child: Text(&quot;Hello, Flutter!&quot;)<br>           .paddAll(16.0), // A way to add padding like the others<br>  );<br>}</pre><p>Adopting this approach makes your Flutter app <strong>scalable, structured, and easier to maintain</strong> — just like modern frameworks in other ecosystems.</p><p>Have you tried extensions_plus? Share your thoughts! 🚀</p><h3>Conclusion</h3><p>extensions_plus is designed to make Flutter development more enjoyable and productive by reducing boilerplate code and improving code readability. It provides a comprehensive set of extensions that cover common use cases in Flutter development, from navigation to widget styling.</p><p>The package is open source and available on pub.dev. Give it a try in your next Flutter project and see how it can improve your development experience!</p><h4>Resources</h4><ul><li><a href="https://pub.dev/packages/extensions_plus">Package on pub.dev</a></li><li><a href="https://github.com/azharbinanwar/extensions_plus">GitHub Repository</a></li><li><a href="https://pub.dev/documentation/extensions_plus/latest/">Documentation</a></li><li><a href="https://github.com/azharbinanwar/extensions_plus/issues">Issue Tracker</a></li></ul><p>Happy coding! 🚀</p><p>#Flutter #Dart #Programming #CleanCode #OpenSource</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73646406371" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is covariant in Dart | Flutter?]]></title>
            <link>https://medium.com/@azharbinanwar/what-is-covariant-in-dart-flutter-3bd180b3a770?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd180b3a770</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[covariant]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 18:51:22 GMT</pubDate>
            <atom:updated>2025-02-09T18:51:22.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2H6uRVPbygmI-aAqs0fS_Q.png" /></figure><h3>Introduction</h3><p>In object-oriented programming, we often work with hierarchies of classes where subclasses need to handle more specific types than their parent classes. Dart’s covariant keyword provides a type-safe way to achieve this specialization. Let&#39;s explore this concept through a practical example of an animal feeding system.</p><h3>Understanding covariant</h3><p><strong>The </strong><strong>covariant keyword allows a method parameter in a subclass to accept a more specific type than the parameter in its superclass.</strong> This is particularly useful when you want to ensure type safety while working with specialized types in your class hierarchy.</p><p>For example, while all animals eat food, carnivores specifically eat meat, and herbivores eat vegetables. Without covariant, we&#39;d need to handle type checking manually or use less specific types, potentially losing type safety.</p><h3>Base Classes: Food and Animal System</h3><pre>// Basic food hierarchy<br>class Food {<br>  final String name;<br>  final double nutrients;<br>  <br>  Food(this.name, this.nutrients);<br>}<br><br>class Meat extends Food {<br>  final bool isCooked;<br>  <br>  Meat(String name, double nutrients, this.isCooked) <br>    : super(name, nutrients);<br>}<br><br>class Vegetables extends Food {<br>  final bool isOrganic;<br>  <br>  Vegetables(String name, double nutrients, this.isOrganic) <br>    : super(name, nutrients);<br>}<br><br>// Animal hierarchy with covariant<br>abstract class Animal {<br>  void eat(covariant Food food);<br>  String get species;<br>}<br><br>class Carnivore extends Animal {<br>  @override<br>  String get species =&gt; &#39;Carnivore&#39;;<br>  <br>  @override<br>  void eat(Meat food) {<br>    if (!food.isCooked) {<br>      print(&#39;$species is eating raw ${food.name}&#39;);<br>    } else {<br>      print(&#39;$species is eating cooked ${food.name}&#39;);<br>    }<br>  }<br>}<br><br>class Herbivore extends Animal {<br>  @override<br>  String get species =&gt; &#39;Herbivore&#39;;<br>  <br>  @override<br>  void eat(Vegetables food) {<br>    if (food.isOrganic) {<br>      print(&#39;$species is eating organic ${food.name}&#39;);<br>    } else {<br>      print(&#39;$species is eating non-organic ${food.name}&#39;);<br>    }<br>  }<br>}</pre><p>Here is the usage of covariant</p><pre>// Animal hierarchy with covariant<br>abstract class Animal {<br>  void eat(covariant Food food);<br>  String get species;<br>}</pre><h3>Usage Examples and Type Safety Demonstrations</h3><pre>void main() {<br>  // Initialize animals<br>  final lion = Carnivore();<br>  final rabbit = Herbivore();<br>  <br>  // Initialize foods<br>  final steak = Meat(&#39;Steak&#39;, 100, true);<br>  final carrot = Vegetables(&#39;Carrot&#39;, 50, true);<br>  final lettuce = Vegetables(&#39;Lettuce&#39;, 30, true);<br>  final beef = Meat(&#39;Beef&#39;, 100, true);<br>  <br>  // Direct usage with correct types<br>  lion.eat(steak);    // ✅ &quot;Carnivore is eating cooked Steak&quot;<br>  lion.eat(carrot);   // ❌ Compile-time error: Wrong food type<br>  <br>  rabbit.eat(lettuce); // ✅ &quot;Herbivore is eating organic Lettuce&quot;<br>  rabbit.eat(beef);    // ❌ Compile-time error: Wrong food type<br><br>  // Working with base class references<br>  final Animal animal1 = Carnivore();<br>  final Animal animal2 = Herbivore();<br>  <br>  animal1.eat(steak);    // ❌ Needs type checking<br>  animal2.eat(lettuce);  // ❌ Needs type checking<br>  <br>  // Proper type checking<br>  if (animal1 is Carnivore) {<br>    animal1.eat(steak);     // ✅ Works after type check<br>  }<br>  <br>  if (animal2 is Herbivore) {<br>    animal2.eat(lettuce);   // ✅ Works after type check<br>  }<br>  <br>  // Working with collections<br>  List&lt;Animal&gt; animals = [lion, rabbit];<br>  <br>  // Proper handling in collections<br>  animals.forEach((animal) {<br>    if (animal is Carnivore) {<br>      animal.eat(steak);      // ✅ Type-safe<br>    } else if (animal is Herbivore) {<br>      animal.eat(lettuce);    // ✅ Type-safe<br>    }<br>  });<br>}</pre><h3>Key Points</h3><ol><li>covariant allows subclasses to specify more precise parameter types</li><li>Type checking is required when working with base class references</li><li>Collections need proper type-checking before specialized operations</li><li>Compile-time safety prevents feeding the wrong food types</li><li>Each animal type maintains its specific food requirements</li></ol><h3>Best Practices</h3><ol><li>Always use type-checking with base class references</li><li>Keep the inheritance hierarchy logical and meaningful</li><li>Use covariant only when specialization is required</li><li>Maintain type safety through proper checks</li><li>Document the expected types and behaviors</li></ol><h3>Conclusion</h3><p>In conclusion, mastering the covariant keyword is a significant step toward writing more robust and maintainable Flutter applications.<strong> By understanding how covariant works, you gain better control over method overriding and type safety — two pillars that enhance code reliability.</strong></p><p>Embracing this advanced feature not only clarifies Dart’s type system but also empowers you to tackle more complex scenarios in your projects. As you continue your Flutter journey, remember that a deep understanding of these foundational concepts is key to building scalable, efficient, and error-resistant applications.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd180b3a770" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Widget Extensions: Streamline Your UI Development]]></title>
            <link>https://medium.com/@azharbinanwar/flutter-widget-extensions-streamline-your-ui-development-d0d540e2d88a?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0d540e2d88a</guid>
            <category><![CDATA[extension-method]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[learn-flutter-widgets]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 07:38:51 GMT</pubDate>
            <atom:updated>2025-01-22T12:15:11.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0llBo3U02-ikk5AIZXi2w.png" /></figure><p>In Flutter development, writing clean, maintainable UI code can be challenging due to deeply nested widget trees and repetitive boilerplate code. Widget extensions offer an elegant solution to this problem by providing a fluent, chainable API for common UI patterns. Let’s explore how these extensions can transform your Flutter development workflow.</p><pre>extension WidgetExtension on Widget {<br>  Widget paddingAll(double value) =&gt; Padding(padding: EdgeInsets.all(value), child: this);<br><br>  Widget padding(EdgeInsets padding) =&gt; Padding(padding: padding, child: this);<br><br>  Widget fill() =&gt; Positioned.fill(child: this);<br><br>  Widget onTap(VoidCallback? onTap) =&gt; GestureDetector(onTap: onTap, child: this);<br><br>  Widget paddingSymmetric({double horizontal = 0.0, double vertical = 0.0}) =&gt;<br>      Padding(padding: EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical), child: this);<br><br>  Widget paddingOnly({<br>    double left = 0.0,<br>    double right = 0.0,<br>    double top = 0.0,<br>    double bottom = 0.0,<br>  }) =&gt;<br>      Padding(<br>        padding: EdgeInsets.only(left: left, right: right, top: top, bottom: bottom),<br>        child: this,<br>      );<br><br>  Widget paddingFromLTRB({required double left, required double right, required double top, required double bottom}) =&gt;<br>      Padding(padding: EdgeInsets.fromLTRB(left, top, right, bottom), child: this);<br><br>  Widget marginAll(double value) =&gt; Padding(padding: EdgeInsets.all(value), child: this);<br><br>  Widget marginSymmetric({required double horizontal, required double vertical}) =&gt;<br>      Padding(padding: EdgeInsets.symmetric(horizontal: horizontal, vertical: vertical), child: this);<br><br>  Widget marginOnly({required double left, required double right, required double top, required double bottom}) =&gt;<br>      Padding(padding: EdgeInsets.only(left: left, right: right, top: top, bottom: bottom), child: this);<br><br>  Widget marginFromLTRB({required double left, required double right, required double top, required double bottom}) =&gt;<br>      Padding(padding: EdgeInsets.fromLTRB(left, top, right, bottom), child: this);<br><br>  Widget center() =&gt; Center(child: this);<br><br>  Widget fit() =&gt; FittedBox(child: this);<br><br>  Widget square(double value) =&gt; SizedBox.square(dimension: value, child: this);<br><br>  Widget materialized({<br>    BorderRadius? borderRadius,<br>  }) =&gt;<br>      Material(<br>        borderRadius: borderRadius,<br>        color: Colors.transparent,<br>        child: this,<br>      );<br><br>  Widget safeArea({<br>    bool left = true,<br>    bool top = true,<br>    bool right = true,<br>    bool bottom = true,<br>  }) =&gt;<br>      SafeArea(left: left, top: top, right: right, bottom: bottom, child: this);<br><br>  Widget showIf(bool value) =&gt; value ? this : const SizedBox.shrink();<br><br>  Widget align([AlignmentGeometry alignment = Alignment.center]) =&gt; Align(alignment: alignment, child: this);<br><br>  Widget expanded({int flex = 1}) =&gt; Expanded(flex: flex, child: this);<br><br>  Widget flexible({int flex = 1}) =&gt; Flexible(flex: flex, child: this);<br><br>  Widget background(Color color) =&gt; Material(color: color, child: this);<br><br>  Widget addDivider({<br>    double height = 1.0,<br>    Color color = Colors.grey,<br>    double indent = 0.0,<br>    double endIndent = 0.0,<br>  }) {<br>    return Column(<br>      mainAxisSize: MainAxisSize.min,<br>      children: [<br>        this,<br>        Divider(<br>          height: height,<br>          color: color,<br>          indent: indent,<br>          endIndent: endIndent,<br>        ),<br>      ],<br>    );<br>  }<br><br>  Widget constrains({<br>    double minWidth = 0.0,<br>    double maxWidth = double.infinity,<br>    double minHeight = 0.0,<br>    double maxHeight = double.infinity,<br>  }) {<br>    return ConstrainedBox(<br>      constraints: BoxConstraints(<br>        minWidth: minWidth,<br>        maxWidth: maxWidth,<br>        minHeight: minHeight,<br>        maxHeight: maxHeight,<br>      ),<br>      child: this,<br>    );<br>  }<br><br>  Widget responsiveConstrains({<br>    alignment = Alignment.topCenter,<br>    double minWidth = 0.0,<br>    double maxWidth = 600.0,<br>    double minHeight = 0.0,<br>    double maxHeight = double.infinity,<br>  }) {<br>    return ConstrainedBox(<br>      constraints: BoxConstraints(<br>        minWidth: minWidth,<br>        maxWidth: maxWidth,<br>        minHeight: minHeight,<br>        maxHeight: maxHeight,<br>      ),<br>      child: this,<br>    ).align(alignment);<br>  }<br><br>  /// update status bar color according to the screens and theme<br>  Widget annotateRegion(BuildContext context, {Color? statusBarColor, Brightness? statusBarIconBrightness, Brightness? statusBarBrightness}) {<br>    Brightness brightness = Theme.of(context).brightness;<br>    return AnnotatedRegion&lt;SystemUiOverlayStyle&gt;(<br>      /// if the value is null, the value of the current scope will be used<br>      /// if the value is not null, the value of the current scope will be replaced<br>      /// status bar colors are used opposite to the theme brightness<br>      value: SystemUiOverlayStyle(<br>        statusBarColor: statusBarColor ?? context.appBarColor,<br>        statusBarIconBrightness: statusBarIconBrightness ?? (brightness == Brightness.light ? Brightness.dark : Brightness.light),<br>        statusBarBrightness: statusBarBrightness ?? brightness,<br>      ),<br>      child: this,<br>    );<br>  }<br><br>  Widget toScrollableList({int itemCount = 10, Axis scrollDirection = Axis.vertical, EdgeInsets padding = EdgeInsets.zero, Widget? separator}) {<br>    List&lt;Widget&gt; items = List.generate(itemCount, (index) =&gt; this);<br>    if (separator != null) {<br>      items = items.expand((element) =&gt; [element, separator]).toList();<br>    }<br><br>    return SingleChildScrollView(<br>      padding: padding,<br>      scrollDirection: scrollDirection,<br>      child: scrollDirection == Axis.vertical ? Column(children: items) : Row(children: items),<br>    );<br>  }<br><br>  Widget toScrollableGrid({<br>    SliverGridDelegate gridDelegate = const SliverGridDelegateWithFixedCrossAxisCount(<br>      crossAxisCount: 2,<br>      crossAxisSpacing: 16.0,<br>      mainAxisSpacing: 16.0,<br>    ),<br>    EdgeInsets padding = EdgeInsets.zero,<br>    int itemCount = 10,<br>    Axis scrollDirection = Axis.vertical,<br>  }) {<br>    return GridView.builder(<br>      primary: false,<br>      shrinkWrap: true,<br>      itemCount: itemCount,<br>      gridDelegate: gridDelegate,<br>      scrollDirection: scrollDirection,<br>      padding: padding,<br>      itemBuilder: (_, __) =&gt; this,<br>    );<br>  }<br><br>  Widget scrollable({Axis scrollDirection = Axis.vertical, EdgeInsets padding = EdgeInsets.zero}) {<br>    return SingleChildScrollView(<br>      scrollDirection: scrollDirection,<br>      padding: padding,<br>      child: this,<br>    );<br>  }<br><br>  Widget toSkeleton({bool? ignoreContainers, bool enabled = true}) {<br>    return Skeletonizer(<br>      enabled: enabled,<br>      ignoreContainers: ignoreContainers,<br>      child: this,<br>    );<br>  }<br>}<br><br>/// 3.27 offers build similar feature like space in column and row<br>extension ColumnExtension on Column {<br>  Column childrenPadding(EdgeInsets padding) {<br>    return Column(<br>      crossAxisAlignment: crossAxisAlignment,<br>      mainAxisAlignment: mainAxisAlignment,<br>      mainAxisSize: mainAxisSize,<br>      textBaseline: textBaseline,<br>      textDirection: textDirection,<br>      verticalDirection: verticalDirection,<br>      children: children.map((e) =&gt; e.padding(padding)).toList(),<br>    );<br>  }<br>}<br><br>/// 3.27 offers build similar feature like space in column and row<br>extension RowExtension on Row {<br>  Row childrenPadding(EdgeInsets padding) {<br>    return Row(<br>      crossAxisAlignment: crossAxisAlignment,<br>      mainAxisAlignment: mainAxisAlignment,<br>      mainAxisSize: mainAxisSize,<br>      textBaseline: textBaseline,<br>      textDirection: textDirection,<br>      verticalDirection: verticalDirection,<br>      children: children.map((e) =&gt; e.padding(padding)).toList(),<br>    );<br>  }<br>}</pre><h3>Core Features and Benefits</h3><h4>1. Layout Manipulation</h4><p>The most frequently used extensions handle basic layout operations:</p><pre>// Instead of nested Padding widgets<br>Text(&quot;Hello&quot;)<br>  .paddingAll(16.0)<br>  .marginSymmetric(horizontal: 8.0, vertical: 16.0)<br>  <br>// Instead of Center and alignment widgets<br>MyWidget()<br>  .center()<br>  .align(Alignment.topLeft)</pre><h4>2. Responsive Design</h4><p>Built-in responsive constraints make it easier to create adaptive layouts:</p><pre>MyContentWidget()<br>  .responsiveConstrains(<br>    maxWidth: 600.0,<br>    alignment: Alignment.topCenter<br>  )<br>  .scrollable()</pre><h4>3. List and Grid Generation</h4><p>Quickly create scrollable lists and grids from any widget:</p><pre>MyListItem()<br>  .toScrollableList(<br>    itemCount: 10,<br>    scrollDirection: Axis.vertical,<br>    padding: EdgeInsets.all(16.0)<br>  )<br><br>MyGridItem()<br>  .toScrollableGrid(<br>    itemCount: 10,<br>    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(<br>      crossAxisCount: 2,<br>      crossAxisSpacing: 16.0<br>    )<br>  )</pre><h4>4. Conditional Rendering</h4><p>Simplify conditional UI logic:</p><pre>MyWidget()<br>  .showIf(someCondition)</pre><h4>5. System UI Integration</h4><p>Handle status bar and system UI customization elegantly:</p><pre>MyScreen()<br>  .annotateRegion(<br>    context,<br>    statusBarColor: Colors.transparent,<br>    statusBarIconBrightness: Brightness.dark<br>  )</pre><h3>Practical Use Cases</h3><h4>1. Form Fields</h4><pre>TextFormField()<br>  .paddingSymmetric(horizontal: 16.0, vertical: 8.0)<br>  .background(Colors.grey[100]!)<br>  .marginAll(8.0)</pre><h4>2. Cards and Containers</h4><pre>MyCardContent()<br>  .materialized(borderRadius: BorderRadius.circular(8.0))<br>  .paddingAll(16.0)<br>  .constrains(maxWidth: 400.0)</pre><h4>3. Scrollable Content</h4><pre>MyContent()<br>  .scrollable(padding: EdgeInsets.all(16.0))<br>  .safeArea()</pre><h3>Performance Considerations</h3><p>These extensions are designed to be lightweight wrappers around Flutter’s built-in widgets. They:</p><ul><li>Don’t create unnecessary widget rebuilds</li><li>Maintain the original widget tree structure</li><li>Add minimal overhead to the application</li></ul><h3>Best Practices</h3><ol><li><strong>Consistent Usage</strong>: Adopt these extensions across your project for consistency.</li><li><strong>Chain Ordering</strong>: Keep a consistent order in your extension chains (e.g., styling → padding → margin → positioning).</li><li><strong>Readability</strong>: Break long chains into multiple lines for better readability.</li><li><strong>Documentation</strong>: Document any custom extensions you add to the set</li></ol><p>⚠️ <strong>Important Note</strong>: These extensions are meant to replace traditional nested widgets. You can always fall back to standard Flutter widgets if they don’t provide the expected behavior.</p><pre>// Might not work as expected:<br>Text(&#39;Hello&#39;).expanded()<br><br>// Better approach:<br>Row(<br>  children: [<br>    Text(&#39;Hello&#39;).expanded()<br>  ]<br>)</pre><h3>Conclusion</h3><p>Widget extensions offer a powerful way to write more maintainable Flutter UI code. They reduce boilerplate, improve readability, and make common UI patterns more accessible. Adopting these extensions in your project can significantly improve your development workflow and code quality.</p><p>Remember to:</p><ul><li>Use extensions consistently across your project</li><li>Keep your chains readable and well-organized</li><li>Document any custom extensions you create</li><li>Consider performance implications in complex chains</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0d540e2d88a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Fixed the Android Studio Update Issue (January 2025)]]></title>
            <link>https://medium.com/@azharbinanwar/how-i-fixed-the-android-studio-update-issue-january-2025-b6d0468ba524?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d0468ba524</guid>
            <category><![CDATA[21]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[ladybugs]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 10:14:03 GMT</pubDate>
            <atom:updated>2025-01-16T10:14:03.175Z</atom:updated>
            <content:encoded><![CDATA[<p>After updating Android Studio to the latest Beta version (Meerkat | 2024.3.1 Nightly 2025–01–14), I encountered a persistent issue that took hours of troubleshooting. If you’re facing a similar problem, I’ve documented the steps that finally worked for me and successfully resolved the issue in two separate projects. Here’s the solution:</p><p>1. Update Your app\build.gradle File</p><p>Ensure the following configurations are present:</p><pre>android {<br>    namespace = &quot;sa.idoc.app&quot;<br>    compileSdk = 35<br>    ndkVersion &quot;25.1.8937393&quot;<br><br>    compileOptions {<br>        sourceCompatibility JavaVersion.VERSION_17<br>        targetCompatibility JavaVersion.VERSION_17<br>    }<br>    kotlinOptions {<br>        jvmTarget = 17<br>    }<br>}</pre><p>These updates align the Java and Kotlin versions with the requirements of the updated Android Studio.</p><p>2. Modify Your settings.gradle File</p><p>Replace the existing plugin versions with the following:</p><pre>id &quot;com.android.application&quot; version &quot;8.3.2&quot; apply false<br>id &quot;org.jetbrains.kotlin.android&quot; version &quot;2.0.20&quot; apply false</pre><p>This ensures compatibility with the new Gradle and Kotlin plugin versions.</p><p>3. Update gradle-wrapper.properties</p><p>Update the distributionUrl to point to the latest Gradle version:</p><pre>distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip</pre><p>This resolves any Gradle version mismatch that may arise after the Android Studio update.</p><h3>How I Found This Solution</h3><p>After struggling to pinpoint the issue, I closely examined my logs, which looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*6NPml8AqML-x2b15U30uJg.png" /></figure><pre>Android Studio Meerkat | 2024.3.1 Nightly 2025-01-14</pre><p>The logs hinted at version incompatibilities, prompting me to dig deeper into Gradle, NDK, and Kotlin configurations. I found a related discussion on <a href="https://github.com/flutter/flutter/issues/156304">this GitHub issue</a>, where user @deakjahan shared a solution that worked perfectly for me.</p><p>You can refer to the original comment <a href="https://github.com/flutter/flutter/issues/156304#issuecomment-2397707812">here</a>.</p><h3>Conclusion</h3><p>Try applying these fixes if you’ve recently updated to the latest Android Studio and encountered similar issues. This approach worked for both of my projects and should help you as well. If you still face issues, feel free to check out the related GitHub discussion or share your experience in the comments.</p><p><strong>GitHub Link</strong>: <a href="https://github.com/flutter/flutter/issues/156304">Flutter Issue #156304</a></p><p>Credit to: <strong>@deakjahan</strong> for the original solution.</p><p>I hope this helps others save hours of troubleshooting! Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d0468ba524" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Future vs FutureOr in Flutter: A Comprehensive Guide]]></title>
            <link>https://medium.com/@azharbinanwar/understanding-future-vs-futureor-in-flutter-a-comprehensive-guide-cb115f1d58cd?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb115f1d58cd</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 07:24:31 GMT</pubDate>
            <atom:updated>2024-07-05T07:24:31.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPs2fdZFi2t6GZ_Fj46JGg.png" /></figure><p>Flutter, with its robust asynchronous programming capabilities, offers two key types for handling asynchronous operations: Future and FutureOr. Understanding the differences and appropriate use cases for each can significantly enhance your code’s efficiency and readability. Let&#39;s dive into what these types are and how to use them effectively.</p><p><strong>What is the Future?</strong></p><p>A Future represents the eventual completion (or failure) of an asynchronous operation. It acts as a placeholder for the eventual result (or error) of that operation.</p><p>Imagine a Future as a letter on its way – you know it&#39;s coming, but you don&#39;t have it yet. The code using the Future needs to handle the asynchronous nature by waiting for it to complete using keywords like async and await or .then and .catchError.</p><p>Here’s a common use case for Future:</p><ul><li><strong>Fetching Data from a Network:</strong> Network requests are inherently asynchronous. You can use a Future to handle the response from an API call, allowing your code to continue execution without blocking the main thread.</li></ul><pre>Future&lt;String&gt; fetchUserData(int userId) async {<br>  final response = await http.get(Uri.parse(&#39;https://api.example.com/users/$userId&#39;));<br>  if (response.statusCode == 200) {<br>    final data = jsonDecode(response.body);<br>    return User.fromJson(data);<br>  } else {<br>    throw Exception(&#39;Failed to fetch user data&#39;);<br>  }<br>}</pre><p>In this example, fetchUserData returns a Future&lt;String&gt;. The calling code can use async and await to handle the asynchronous nature and process the user data after it&#39;s received.</p><p><strong>Introducing FutureOr: A Flexible Cousin</strong></p><p>FutureOr introduces more flexibility when dealing with asynchronous operations. It represents a value that can be either a Future or the actual value itself.</p><p>Think of it like checking your mailbox – you might find a letter (the Future), or the mail might already be delivered (the actual value).</p><p>Here’s where FutureOr shines:</p><ul><li><strong>Handling Pre-fetched Data:</strong> If you have data readily available (e.g., from a cache), you can use FutureOr to return the value directly, avoiding unnecessary asynchronous operations.</li></ul><pre>FutureOr&lt;String&gt; getCachedValue(String key) {<br>  final cachedData = prefs.getString(key);<br>  if (cachedData != null) {<br>    return cachedData; // Return cached value directly<br>  } else {<br>    // Fallback to asynchronous database fetch<br>    return _fetchValueFromDatabase(key);<br>  }<br>}<br><br>Future&lt;String&gt; _fetchValueFromDatabase(String key) async {<br>  // Simulate database operation<br>  await Future.delayed(Duration(seconds: 1));<br>  return &#39;Fetched from Database!&#39;;<br>}</pre><p>In this example, getCachedValue returns a FutureOr&lt;String&gt;. It checks for cached data first and, if available, returns it directly. Otherwise, it falls back to asynchronously fetching the value and returns a Future. This simplifies the calling code&#39;s logic.</p><h4>Key Differences</h4><p><strong>Usage</strong>:</p><ul><li><strong>Future</strong>: Always represents a value that will be available in the future, making it suitable for always-async operations.</li><li><strong>FutureOr</strong>: Can represent an immediate value or a future value, useful for functions that might return synchronously or asynchronously.</li></ul><p><strong>Flexibility</strong>:</p><ul><li><strong>Future</strong>: Clearly indicates asynchronous operations, ensuring that the async flow is explicit and easy to follow.</li><li><strong>FutureOr</strong>: Reduces boilerplate and simplifies code when functions may not always need to perform asynchronous operations.</li></ul><h4>Benefits of Using Future and FutureOr</h4><p><strong>Future</strong>:</p><ul><li>Ensures a clear, predictable async flow.</li><li>Ideal for operations that are always asynchronous.</li></ul><p><strong>FutureOr</strong>:</p><ul><li>Provides versatility by handling both synchronous and asynchronous returns.</li><li>Reduces code complexity and improves readability when functions have mixed return types.</li></ul><h3>Conclusion</h3><p>Understanding when to use Future and FutureOr can significantly improve your Flutter code&#39;s efficiency and readability. While Future is great for strictly asynchronous operations, FutureOr provides the versatility needed for functions that might need to return either immediately or after some delay. By choosing the right type for your needs, you can write more concise and effective asynchronous code in Flutter.</p><p>Please share your thoughts in comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb115f1d58cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Generic Classes in Flutter Bloc: Enhancing Code Reusability and Flexibility]]></title>
            <link>https://medium.com/@azharbinanwar/exploring-generic-classes-in-flutter-bloc-enhancing-code-reusability-and-flexibility-1011184b75f6?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/1011184b75f6</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[flutter-bloc]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[bloc]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 17:53:15 GMT</pubDate>
            <atom:updated>2024-04-15T19:43:00.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0oK6eH0IO5vVfqaoLQ65Q.png" /></figure><h3>Introduction</h3><p>State management is a crucial aspect of building dynamic and reactive applications in Flutter development. The BLoC (Business Logic Component) pattern provides a structured approach to managing the state. However, implementing BLoC for different data types can result in repetitive code. To avoid this, generic Cubits offer a powerful way to simplify state management while still being flexible.</p><h3><strong>Generic Cubits: A Boon for Reusability</strong></h3><p>I’ll show you some examples of how we can effectively use it. These classes utilize generics (T), allowing them to work with various data types. <strong><em>This eliminates the need for creating numerous Cubit subclasses specific to different data types, promoting code reusability and maintainability</em></strong>.</p><p>Let’s start before getting bored 😀.</p><pre>flutter_bloc: ^8.1.5</pre><p>Generic Cubit with Non-Nullable value</p><pre>class Handler&lt;T&gt; extends Cubit&lt;T&gt; {<br>  Handler(super.initialState);<br><br>  void init(T state) =&gt; emit(state);<br><br>  void update(T state) =&gt; emit(state);<br>}</pre><p>I’ve added two basic methods init and update as per my requirement but it can be changed or updated according to your requirements.</p><p>Let me show its implementation with a simple counter app.</p><p>How should you declare a cubit with an integer value?</p><p>Set any default value because we’ve used a non-nullable cubit?</p><pre>// Declaration of the Cubit with an integer value <br>// as we are certain it will be an integer.<br>final Handler&lt;int&gt; _handler = Handler(0);<br><br><br>//Incrementing value<br><br>_handler.update(_handler.state + 1)<br><br>// Decrementing value<br><br>_handler.update(_handler.state - 1),</pre><p>How you’ve to use it as a builder:</p><pre>  BlocBuilder&lt;Handler&lt;int&gt;, int&gt;(<br>    bloc: _handler,<br>    builder: (context, state) {<br>      return Text(<br>        &#39;$state&#39;,<br>        style: Theme.of(context).textTheme.displayLarge,<br>      );<br>    },<br>  );</pre><p>Counter.dart class</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_app/bloc_and_generic/helper.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br><br>class CounterPage extends StatelessWidget {<br>  CounterPage({super.key});<br><br>// Declaration of the Cubit with an integer value <br>// as we are certain it will be an integer<br>  final Handler&lt;int&gt; _handler = Handler(0);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Counter Page&#39;),<br>      ),<br>      body: Center(<br>        child: Row(<br>          mainAxisSize: MainAxisSize.min,<br>          children: [<br>            IconButton(<br>              icon: const Icon(Icons.add, size: 36.0),<br>              onPressed: () =&gt; _handler.update(_handler.state + 1),<br>            ),<br>            const SizedBox(width: 12.0),<br>            BlocBuilder&lt;Handler&lt;int&gt;, int&gt;(<br>              bloc: _handler,<br>              builder: (context, state) {<br>                return Text(<br>                  &#39;$state&#39;,<br>                  style: Theme.of(context).textTheme.displayLarge,<br>                );<br>              },<br>            ),<br>            const SizedBox(width: 12.0),<br>            IconButton(<br>              icon: const Icon(Icons.remove, size: 36.0),<br>              onPressed: () =&gt; _handler.update(_handler.state - 1),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*VhHvm5tK68Z0TqXZSKFznQ.gif" /></figure><p>Let me show another example with the same Generic Handler</p><p>I’ve designed a webview page and want to show the web page loading progress and I used the same Handler instead of creating a new cubit or use setState.</p><pre>final Handler&lt;num&gt; _progressHelper = Handler&lt;num&gt;(0.0);</pre><p>Now I’ve used the Handler with num it so it can handle double and integer at the same time.</p><pre>class WebviewPage extends StatefulWidget {<br>  final String url;<br>  final Map&lt;String, String&gt; headers;<br>  final bool showProgress;<br><br>  const WebviewPage({<br>    required this.url,<br>    this.headers = const {},<br>    final bool? showProgress,<br>  }) : showProgress = showProgress ?? true;<br><br>  @override<br>  State&lt;WebviewPage&gt; createState() =&gt; _WebviewPageState();<br>}<br><br>class _WebviewPageState extends State&lt;WebviewPage&gt; {<br>  late WebViewController _controller;<br>  final Handler&lt;num&gt; _progressHelper = Handler&lt;num&gt;(0.0);<br><br>  @override<br>  void initState() {<br>    super.initState();<br><br>    _controller = WebViewController()<br>      ..setJavaScriptMode(JavaScriptMode.unrestricted)<br>      ..setNavigationDelegate(<br>        NavigationDelegate(<br>          onProgress: _progressHelper.update,<br>          onPageStarted: (String url) {<br>            /// update the default behavior of the web-view if needed<br>          },<br>          onPageFinished: (String url) {<br>            /// update the default behavior of the web-view if needed<br>          },<br>          onWebResourceError: (WebResourceError error) {},<br>        ),<br>      )<br>      ..loadRequest(<br>        Uri.parse(widget.url),<br>        headers: widget.headers,<br>      );<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Webview Page&#39;),<br>      ),<br>      body: Column(<br>        children: [<br>          BlocBuilder&lt;Handler&lt;num&gt;, num&gt;(<br>            bloc: _progressHelper,<br>            builder: (context, state) =&gt; AnimatedContainer(<br>              duration: const Duration(milliseconds: 300),<br>              height: state == 100 ? 0 : 1.5,<br>              child: LinearProgressIndicator(minHeight: 1.5, value: state / 100),<br>            ),<br>          ),<br>          Expanded(<br>            child: WebViewWidget(<br>              controller: _controller..setBackgroundColor(Colors.white),<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>I’ve used the same Handler to manage the custom progress bar in my webview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*6X9HyrSD6ynZJ_jwSGdDYQ.gif" /></figure><p>Combining BloC with Generic classes can significantly reduce code in our projects.</p><p>It can be used with MultiBlocProvider but on behalf of data type, one data type will be used everywhere as a single instance.</p><pre>  return MultiBlocProvider(<br>      providers: [<br>        BlocProvider(create: (context) =&gt; Handler&lt;int&gt;(0)),<br>        BlocProvider(create: (context) =&gt; Handler&lt;num&gt;(0)),<br>      ],<br>      child: const MaterialApp(<br>        title: &#39;Flutter Demo&#39;,<br>        debugShowCheckedModeBanner: false,<br>        home: MainPage(),<br>      ),<br>    );</pre><p>How it would be used</p><pre>final Handler&lt;int&gt; handler = BlocProvider.of&lt;Handler&lt;int&gt;&gt;(context);<br>final Handler&lt;num&gt; handler1 = BlocProvider.of&lt;Handler&lt;num&gt;&gt;(context);<br><br>  BlocBuilder&lt;Handler&lt;num&gt;, num&gt;(<br>// in case of multiple provider install we don&#39;t need to link with builder<br>    // bloc: handler,<br>    builder: (context, state) {<br>      return Text(<br>        &#39;$state&#39;,<br>        style: Theme.of(context).textTheme.displayLarge,<br>      );<br>    },<br>  ),</pre><p>We can use nullable data types as per the requirements, but it depends on what we are supposed to do.</p><pre>class Helper&lt;T&gt; extends Cubit&lt;T?&gt; {<br>  Helper([super.initialState]);<br><br>  void init(T? state) =&gt; emit(state);<br><br>  void update(T? state) =&gt; emit(state);<br>  // reset can be add as an extra method to set value to null.<br>  void reset() =&gt; emit(null);<br>}</pre><p>Generic (T) means any it can be Primitive DataType or non-Primitive DataType, enums, etc. We can go it with as per our requirement and use it as a helper to avoid creating a lot of Cubit in code for no reason.</p><pre>final Helper&lt;MyEnum&gt; helperEnum = Helper&lt;MyEnum&gt;(MyEnum.v);<br>final Helper&lt;User&gt; helperUser = Helper&lt;User&gt;(User.guest());<br>final Helper&lt;double&gt; helperDoulbe = Helper&lt;double&gt;(0.0);<br>final Helper&lt;bool&gt; helperBool = Helper&lt;bool&gt;(false/true);</pre><h3>Conclusion:</h3><p>In Flutter development, using generic classes within Flutter Bloc brings simplicity and flexibility to state management. By employing generics, developers can handle various data types efficiently, reducing code redundancy and promoting reusability. Whether managing counter states or monitoring webview loading progress, generic Cubits offer a versatile solution. Embracing this approach streamlines development, making code cleaner and more maintainable. Let’s leverage the power of generics in Flutter Bloc to build dynamic and scalable applications with ease.</p><p>Have you used generic Cubits in your Flutter projects? What are your thoughts on this approach? Share your experiences, questions, or suggestions in the comments below. Don’t forget to give this article a clap if you found it helpful!</p><p><strong>Happy Coding 😃</strong></p><p>Find the Repository here</p><p><a href="https://github.com/azharbinanwar/flutter_app">GitHub - azharbinanwar/flutter_app</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1011184b75f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Performance Optimization Tips for Dart | Flutter.]]></title>
            <link>https://medium.com/@azharbinanwar/flutter-performance-optimization-tips-for-dart-flutter-4e91d5e16335?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e91d5e16335</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 06:18:26 GMT</pubDate>
            <atom:updated>2024-03-21T06:19:42.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QDcLcgbMjzxMppLFoSyaA.png" /></figure><h4>Table of content</h4><blockquote>Unveiling the Power of const Efficient Instances</blockquote><blockquote>Prefer ListView.builder or CustomScrollView (Slivers) over SingleChildScrollView</blockquote><blockquote>Helper Functions vs Widgets</blockquote><h3><strong>Unveiling the Power of </strong>const<strong> Efficient Instances</strong></h3><p>In Dart, const isn&#39;t just for unchanging values. It can also create a single instance of an object with identical properties, saving memory and boosting performance!</p><p><strong>How It Works:</strong></p><ul><li>Declare a class with const constructors.</li><li>Create instances using const before the variable name.</li><li>Dart reuses the same instance for identical properties.</li></ul><p><strong>Example:</strong></p><pre>class User {<br>  final String name;<br>  final int age;<br>  const User(this.name, this.age);<br>}<br><br>void main() {<br>  const user1 = const User(&#39;Alice&#39;, 30);<br>  User user2 = const User(&#39;Alice&#39;, 30); // Same instance as user1!<br>  User user3 = User(&#39;Alice&#39;, 30); // Different instance<br>  print(user1 == user2); // true<br>  print(user1 == user3); // false<br>}</pre><p><strong>Benefits:</strong></p><ul><li><strong>Memory Efficiency:</strong> Objects created with const are compile-time constants. If the same constant is used multiple times in the code, Dart ensures that only one instance is created in memory, reducing memory usage.</li><li><strong>Performance Boost:</strong> Since const objects are known at compile-time and are shared, operations involving these constants can be optimized for faster execution. Comparisons and operations with shared instances are quicker.</li><li><strong>Immutability:</strong> const objects are immutable, meaning their values cannot be changed after they are created. This enhances code safety by preventing accidental modifications, especially during runtime.</li></ul><p><strong>Best Practices:</strong></p><ul><li>Use const for objects with fixed properties (e.g., UI elements, configuration data).</li><li>Consider const for collections and maps with known, unchanging contents.</li><li>Be mindful of object size and frequency of use when applying const.</li></ul><p>Here are some common properties and widgets that can easily marked as const.</p><pre>const Text(&#39;const if possible);<br>const YourWidget();<br>const EdgeInsets.all(8.0);<br>const EdgeInsets.symmetric(horizontal: 16.0);</pre><h3>Prefer ListView.builder or CustomScrollView (Slivers) over SingleChildScrollView</h3><h4><strong>SingleChildScrollView:</strong></h4><p><strong>Benefits</strong></p><ul><li>Straightforward implementation — perfect for getting started with scrolling.</li><li>Well-suited for basic scrolling needs.</li></ul><p><strong>Drawbacks</strong></p><ul><li><strong>Renders Entire Content:</strong> SingleChildScrollView renders the entire child widget upfront, even if only a portion is visible on the screen. This can lead to performance issues on devices with limited memory or when dealing with large lists.</li><li><strong>Inefficient Scrolling:</strong> As the entire content is rendered, scrolling becomes less efficient. The device needs to update all rendered elements during scrolling, even those outside the visible area.</li></ul><h4><strong>ListView.builder/CustomScrollView with Slivers:</strong></h4><ul><li><strong>Lazy Loading:</strong> These approaches only render the visible elements of the list on the screen at a time. As the user scrolls, additional items are loaded and rendered on demand. This significantly improves memory usage and scrolling performance, especially for long lists.</li><li><strong>Efficient Scrolling:</strong> Only the elements currently in the viewport are updated during scrolling, leading to a smoother and more responsive scrolling experience.</li></ul><blockquote><strong>ListView.builder and CustomScrollView differ in their implementation. However, in terms of performance and lazy loading, they function in a similar manner.</strong></blockquote><p>Here’s a breakdown comparing helper functions and widgets in Flutter development:</p><p><strong>Choosing the Right Approach:</strong></p><ul><li><strong>Simple Scrolling:</strong> If your scenario involves a single scrollable element, SingleChildScrollView is the simpler choice due to its ease of use.</li><li><strong>Large Datasets:</strong> When dealing with extensive lists or grids, prioritize ListView.builder to benefit from its performance optimizations.</li></ul><h3><strong>Helper Functions vs Widgets</strong></h3><h4><strong>Helper Functions</strong></h4><p><strong>Purpose:</strong> Reusable blocks of code that perform specific tasks within a widget’s build method.</p><p><strong>Benefits:</strong></p><ul><li>Reduce code duplication within a single widget.</li><li>Improve readability by separating complex logic.</li></ul><p><strong>Drawbacks:</strong></p><ul><li><strong>Performance:</strong> The entire widget tree rebuilds upon state changes, even for minor UI updates (can be inefficient for complex UIs).</li><li><strong>Testability:</strong> Testing helper methods often requires mocking dependencies within the widget.</li><li><strong>Maintainability:</strong> Can become difficult to manage complex logic within functions, potentially leading to bugs related to context.</li></ul><h4><strong>Widgets:</strong></h4><p><strong>Purpose:</strong> Reusable UI components that represent a portion of the application’s visual elements and handle their state.</p><p><strong>Benefits:</strong></p><ul><li><strong>Improved Performance:</strong> Only the specific widget rebuilds when its state changes, leading to better performance.</li><li><strong>Enhanced Testability:</strong> Easier to isolate and test individual widgets with clear dependencies.</li><li><strong>Better Maintainability:</strong> Promote code organization and separation of concerns, making the codebase more manageable.</li></ul><p><strong>Drawbacks:</strong></p><ul><li><strong>Increased Code:</strong> Requires writing separate widget classes, potentially leading to a slightly larger codebase initially.</li></ul><p><strong>Choosing the Right Approach:</strong></p><ul><li>Favor <strong>widgets</strong> for most UI-related functionalities.</li><li>Reserve <strong>helper functions</strong> for smaller, non-UI-related logic within a widget.</li></ul><h4>Conclusions</h4><p>With its in-depth exploration of const optimization and scrolling techniques in Flutter, this article equips developers with valuable insights and practical tips for improving their Dart projects’ efficiency and performance. By embracing const efficiency and adopting the recommended practices, developers can elevate their app development endeavors to new heights of success.</p><p><strong>Thank you for taking the time to read this article. If you have any feedback or corrections, please let me know in the comments below. I am always looking for ways to improve my writing and provide better content for my readers.</strong></p><p><strong>If you found this article helpful, please show your support by giving it a round of claps. Your feedback and support motivate me to continue creating valuable content.</strong></p><p><strong>Find more articles</strong></p><ul><li><a href="https://medium.com/@azharbinanwar/coding-made-easy-using-handy-extensions-on-buildcontext-46283b3655be">Coding made easy using handy extensions on BuildContext.</a></li><li><a href="https://medium.com/@azharbinanwar/what-is-the-difference-between-var-and-dynamic-dart-flutter-1cdbbd8018e6">What is the difference between “var” and “dynamic” | Dart | Flutter?</a></li><li><a href="https://medium.com/@azharbinanwar/change-the-app-theme-using-flutter-bloc-hydrated-bloc-42d091482829">Change the App theme using Flutter Bloc (Hydrated Bloc)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e91d5e16335" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the difference between “var” and “dynamic” | Dart | Flutter?]]></title>
            <link>https://medium.com/@azharbinanwar/what-is-the-difference-between-var-and-dynamic-dart-flutter-1cdbbd8018e6?source=rss-6e819b7bb292------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdbbd8018e6</guid>
            <category><![CDATA[var]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dynamic-variables]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Azhar Ali]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 15:31:50 GMT</pubDate>
            <atom:updated>2024-02-20T15:58:04.189Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woNu2xnYkudllPIrgHyI0g.png" /></figure><p>Both var and dynamic are used to declare variables in Flutter, but they have distinct behaviors and should be chosen carefully for different situations:</p><h3>Var:</h3><p><strong>Use case:</strong> Used when you want the compiler to <strong>determine the type of the variable based on the value assigned to it</strong>.</p><p><strong>Behavior:</strong></p><ul><li>Once a type is initiated, it remains fixed and cannot be altered. Attempting to assign a value of a <strong>different type</strong> will trigger an error in the program.</li><li>Provides some level of type safety <strong>at compile time</strong> because the compiler checks the assigned value type.</li></ul><p><strong>Example:</strong></p><pre>var myString = &quot;Hello&quot;; // Inferred type is String<br>myString = 10; // Error: type mismatch -&gt; Runtime error</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gos4hHDxw7rrnzXbFegU6A.png" /></figure><h3>Dynamic<strong>:</strong></h3><p><strong>Use case:</strong> Used when you <strong>know the variable will hold values of different types at different times</strong>, or you want to <strong>completely disable type checking at compile time</strong>.</p><p><strong>Behavior:</strong></p><ul><li>Allows assigning <strong>any type of value</strong> to the variable.</li><li>No type safety at compile time, potential runtime errors if an incompatible type is used.</li><li>Should be used <strong>sparingly and with caution</strong> due to the lack of type safety.</li></ul><p><strong>Example:</strong></p><pre>dynamic anyValue = &quot;Hello&quot;;<br>anyValue = 10; // No error, but potential runtime exception later if used incorrectly</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAfe4euw5JwbuVOZX3It9A.png" /></figure><h3><strong>Key differences to remember:</strong></h3><ul><li><strong>Type Safety:</strong> var offers partial type safety at compile time, while dynamic disables it completely.</li><li><strong>Flexibility:</strong> dynamic is more flexible but carries the risk of runtime errors due to type mismatch.</li></ul><p><strong>Best Practices:</strong></p><ul><li>Use var when the type is clear from the initial assignment and won&#39;t change.</li><li>Use dynamic only when necessary and handle potential type mismatches carefully.</li><li>For better type safety and code clarity, prefer explicitly declaring the variable type using keywords like String, int, etc.</li></ul><h3>Conclusion: Know Your Types!</h3><p>Remember, var guesses the type, offering safety when it stays the same. dynamic Let you mix it up, but be careful not to mess it up! Choose what fits your needs, but always keep your code clean and safe.</p><p>Happy coding!</p><ul><li><a href="https://medium.com/@azharbinanwar/coding-made-easy-using-handy-extensions-on-buildcontext-46283b3655be">Coding made easy using handy extensions on BuildContext.</a></li><li><a href="https://medium.com/@azharbinanwar/change-the-app-theme-using-flutter-bloc-hydrated-bloc-42d091482829">Change the App theme using Flutter Bloc (Hydrated Bloc)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cdbbd8018e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>