Navigation

Sunday 13 August 2023

Flutter : Simple Example of State Management with flutter_riverpod

In the world of Flutter app development, efficient state management is a key factor in building responsive and user-friendly applications. With various state management solutions available, developers often find themselves navigating through a maze of options. One solution that has gained significant attention and praise is flutter_riverpod

Project Structure 



Step 1: Install Package

             $ flutter pub add flutter_riverpod 

        Click here to get the latest version


Step 2: Add the following code to your main.dart file.   

The ProviderScope widget, provided by the Riverpod state management framework in Flutter, serves as a container for organizing and managing the state of your application. By wrapping your app's main widget with ProviderScope, you create a controlled environment where you can define and use various state providers seamlessly. This allows you to efficiently manage data across different parts of your app while promoting modularity and reusability.

 void main() {
runApp(const ProviderScope(child: MainApp()));
}

       Below, you'll find the entire code for this page. You can simply copy and paste it as-is:

import 'package:flutter/material.dart';
import 'package:flutter_application_riverpod/home_page.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
  runApp(
    const ProviderScope(child: MainApp()),
  );
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    /// Providers are declared globally and specify how to create a state
    final counterProvider = StateProvider((ref) => 0);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: const Text("RiverPod"),
        ),
        body: const Center(
          child: HomePage(),
        ),
      ),
    );
  }
}


Step 3: home_page.dart 

Please copy and paste the entire code for the "home_page.dart" to ensure you have the complete implementation of the home page.

The provided code exemplifies the use of `flutter_riverpod` for efficient state management in a Flutter app. It showcases a `HomePage` widget, equipped to consume state via Riverpod. Within the widget's state, the `ref.watch(counterProvider)` retrieves and displays the current count value managed by the `counterProvider` state provider. The widget also features an "Increment" button that, when pressed, triggers the `counterProvider`'s `increment` method to increase the count by 2. This concise yet powerful setup illustrates how Riverpod simplifies state management, enabling widgets to access and update app state with ease.



import 'package:flutter/material.dart';
import 'package:flutter_application_riverpod/providers/count_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class HomePage extends ConsumerStatefulWidget {
  const HomePage({super.key});

  @override
  ConsumerState<HomePage> createState() => _HomePageState();
}

class _HomePageState extends ConsumerState<HomePage> {
  @override
  Widget build(BuildContext context) {
    final count = ref.watch(counterProvider);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(count.toString()),
        ElevatedButton(
          onPressed: () {
            ref.read(counterProvider.notifier).increment(2);
          },
          child: const Text(" Count "),
        )
      ],
    );
  }
}


Step 4: Please copy and paste the code from the 'count_provider.dart' file that contains the provider implementation.

The provided code snippet highlights the core elements of `flutter_riverpod` state management. It introduces a `Counter` class that extends `StateNotifier<int>` to manage an integer state, initially set to 0. The class contains an `increment` method that adds a specified value to the state. The `counterProvider` is defined as a `StateNotifierProvider`, creating an instance of `Counter` to manage the state.


import 'package:flutter_riverpod/flutter_riverpod.dart';

class Counter extends StateNotifier<int> {
  Counter() : super(0);
  void increment(int val) => state += val;
}

final counterProvider = StateNotifierProvider((ref) {
  return Counter();
});



To sum it up, `flutter_riverpod` is like a powerful helper for managing how your Flutter app stores and uses information. It makes things easier by organizing data in a neat and organized way. Using `flutter_riverpod`, you can control different parts of your app better, keep your code cleaner, and even share data between different parts of your app more smoothly. Just like a helpful guide on a journey, `flutter_riverpod` takes the stress out of managing your app's data, making your app-building adventure smoother.

Result :


    



No comments:

Post a Comment