Home Blog Page 2

Difference between SharedFlow, StateFlow, LiveData in kotlin

0
Kotlin LiveData, StateFlow, SharedFlow
Kotlin LiveData, StateFlow, SharedFlow

In Kotlin Language SharedFlow, StateFlow, and LiveData are classes that comes with Kotlin Coroutines library which are basically used for communication between component in android application in an asynchronous way. However, there are many key differences in terms of their functionality & use cases.

Difference between SharedFlow, StateFlow, LiveData

1. Kotlin LiveData

In Kotlin language LiveData is a Data Model Class used to hold data and is designed to continously observed by it’s UI components may be activities and fragments. Kotlin LiveData is designed to hold and keep observing data that can be attached to the lifecycle of android component such as Activity or a Fragment. In Other words LiveData automatically handles updates to the UI Component when there are active observers and stops updates when there are no active observers, this helps us in preventing memory leaks. Note that LiveData is not a component or feature of Kotlin Coroutines library. Code Example Below

2. Kotlin Stateflow

In Kotlin StateFlow is a part asynchronous event stream, non-blocking I/O Stream that updates all the subsequent states and it’s current state of the emited data to i;s observers. As I said StateFlow is also a part of Kotlin coroutines library that gives a way to handle and represent state-based data flows. In Kotline StateFlow is used in ViewModel to immediatly update when the state changes to UI components. You might be wondering StateFlow seems similar to LiveData but it offers more flexibility, specially when it is combined with coroutines, as it support you to get control over data emission and transformation. Code Example Below

3. Kotlin Sharedflow

In Kotlin SharedFlow is another way to handle asynchronous stream, non-blocking updates, but unlike as we saw in StateFlow, When a observer starts observing SharedFlow does not emit it’s current state. SharedFlow is been designed for use cases when the initial state is not critical or you can ignore it. SharedFlow is designed in such a way that it allows multiple collectors to receive the emitted values concurrently. Suppose you have multiple subscribers and you want to broadcast data to all the subscribers we can use SharedFlow in Kotlin. Code Example Below



Kotlin LiveData Example

Here is a simple example how to integrate kotlin LiveData

1. Add LiveData dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
}

2. Create a class of which data you want to observe:

data class User(val name: String, val age: Int)

3. Create ViewModel Class that contains a LiveData Object

class UserViewModel : ViewModel() {
    private val _user = MutableLiveData<User>()
    val user: LiveData<User> get() = _user

    fun updateUser(newUser: User) {
        _user.value = newUser
    }
}

4. Now Finally you can keep observe changes of the ‘user’ LiveData Object in your Activity

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<UserViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel.user.observe(this, { user ->
            // Update the UI with the new user data
        })

        // Call the update function to trigger the observer
        viewModel.updateUser(User("John Doe", 30))
    }
}


Kotlin Stateflow Example

Here is a simple example how to use kotlin StateFlow into your android application:

1. Add StateFlow dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}

2. Create a class of which data you want to observe:

data class User(val name: String, val age: Int)

3. Create ViewModel Class that contains a StateFlow Object:

class UserViewModel : ViewModel() {
    private val _user = MutableStateFlow(User("", 0))
    val user: StateFlow<User> get() = _user

    fun updateUser(newUser: User) {
        _user.value = newUser
    }
}

4. Now Finally you can keep observe changes of the ‘user’ StateFlow Object in your Activity or in Fragment by using coroutunes:

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<UserViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            viewModel.user.collect { user ->
                // Update the UI with the new user data
            }
        }

        // Call the update function to trigger the observer
        viewModel.updateUser(User("John Doe", 30))
    }
}


Kotlin Sharedflow Example

Here is a simple example How to use kotlin SharedFlow into your android application:

1. Add SharedFlow dependencies in your android kotlin `build.gradle` file under dependencies section:

dependencies {
    def lifecycle_version = "2.4.0-alpha03"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
}

2. Create a class of which data you want to emit:

data class Message(val text: String)

3. Create ViewModel Class that contains a ShareFlow Object:

class MessageViewModel : ViewModel() {
    private val _messages = MutableSharedFlow<Message>()
    val messages: SharedFlow<Message> get() = _messages

    fun sendMessage(message: Message) {
        viewModelScope.launch {
            _messages.emit(message)
        }
    }
}

4. Now Finally you can keep observe and collect the emitted data/message/changes of the ‘user’ StateFlow Object in your Activity or in Fragment by using coroutunes:

class MyActivity : AppCompatActivity() {
    private val viewModel by viewModels<MessageViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launch {
            viewModel.messages.collect { message ->
                // Do something with the message
            }
        }

        // Call the send function to emit a new message
        viewModel.sendMessage(Message("Hello, world!"))
    }
}

Exploring the Power of Flutter InAppWebView

0
flutter in app webview

Hi Guy’s Welcome to Proto Coders Point.

Are you looking for a easiest way to integrate InApp WebView in Futter app? Now need to research anymore! In this Flutter Article blog, we will be exploring Flutter InAppWebView. From understanding what web views and headless web views are.

Flutter is booming now a days as it has revolutionized the way that the developers are create mobile applications as well as web, desktop using flutter frameware that too with its fast development times and excellent performance capabilities. Flutter framework has the ability to integrate webviews seamlessly into the Flutter application. Flutter_InAppWebView is a powerful package using which a flutter developer can create highly interactive and responsive web-embedded apps to show external third party website pages into flutter app itself.


What is webview in Flutter?

Support you are building a Flutter Application, and want to show a external website page into the app for this you can make use of Flutter Webview. Basically a Web View allows a developers to embed a web page into a mobile application.

What is headless WebView?

A Headless WebView, is basically a Webview that don’t display any content from the web page. Instead the website/web page content get’s loaded at background and the developers can use it to get data from the website and use it for building flutter app. This headless Webview is now a days used for web-based API’s.

Adding the InAppWebView Widget into your Flutter App

Integrating InAppWebView widget into your Flutter app is much easy then you think. Now with just a few lines of code, You can build a awesome web-embedded Flutter Application where you can load you website into flutter app.

Integrating InApp Webview in Flutter App – Example

To Add InApp Webview into flutter app we will make use of flutter_inappwebview library, This flutter package will help you to open an in-app browser window.

InAppWebView Widget Syntax

InAppWebView(
                initialUrlRequest: URLRequest(
                  url: Uri.parse("https://protocoderspoint.com/")
                ),
                onWebViewCreated: (InAppWebViewController controller){
                  inAppWebViewController = controller;
                },
                onProgressChanged: (InAppWebViewController controller , int progress){
                  setState(() {
                    _progress = progress / 100;
                  });
                },
  ),

In InAppWebView widget there are various properties though which you can customize WebView in Flutter, Out of all those i have make used of:

initialUrlRequest: used to load a website or web page through URL.

onWebViewCreated(): This property is used to take control to the webview, Using this the flutter developer can attach a InAppWebViewController so that developer can create a controller for the webview and handle it.

onProgressChanged(): This function is been used to get the progress of how much percentage the website is loaded.


Complete Source Code Example – Flutter InAppWebView

In Below Code I have make used of a Stack Widget so that I can show a Webview and a progress indicator, Through Progress Indicator the app user can understand how much percentage of webview is loaded.

To handle webview to navigate to previous page that the user has open in the webview, I am using WillPopScope Widget to check on backpress is the webview can go back, if it can go back then go back one step to previous Web Page within the WebView.

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class MyWebsite extends StatefulWidget {
  const MyWebsite({Key? key}) : super(key: key);

  @override
  State<MyWebsite> createState() => _MyWebsiteState();
}

class _MyWebsiteState extends State<MyWebsite> {

  double _progress = 0;
  late InAppWebViewController  inAppWebViewController;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{

        var isLastPage = await inAppWebViewController.canGoBack();

        if(isLastPage){
          inAppWebViewController.goBack();
          return false;
        }

        return true;
      },
      child: SafeArea(
        child: Scaffold(
          body: Stack(
            children: [
              InAppWebView(
                initialUrlRequest: URLRequest(
                  url: Uri.parse("https://protocoderspoint.com/")
                ),
                onWebViewCreated: (InAppWebViewController controller){
                  inAppWebViewController = controller;
                },
                onProgressChanged: (InAppWebViewController controller , int progress){
                  setState(() {
                    _progress = progress / 100;
                  });
                },
              ),
              _progress < 1 ? Container(
                child: LinearProgressIndicator(
                  value: _progress,
                ),
              ):SizedBox()
            ],
          ),
        ),
      ),
    );
  }
}

Flutter InAppWebView Example

Video Tutorial

How to change Flutter android minSdkVersion & targetSdkVersion

0
How to Change minSdkVersion & TargetSdkVersion flutter sdk
How to Change minSdkVersion & TargetSdkVersion flutter sdk

Hi Guy’s Welcome to Proto Coders Point, In this article let’s checkout how to change minSdkVersion, targetSdkVersion, compileSdkVersion of your flutter project android module, follow below steps:

Flutter Change minSdkVersion, TargetSdkVersion

Step 1: Go to path where you have kept or installed flutter sdk, or where you have extracted flutter sdk zip file, May be at path:

C:\flutter

Step 2: Follow the below path to navigate to flutter.gradle file

C:\flutter\packages\flutter_tools\gradle

Step 3: search for flutter.gradle file in gradle folder

The complete path to file “flutter.gradle” is as below:

C:\flutter\packages\flutter_tools\gradle\flutter.gradle

Open the file in any editor

In this file, There is a class “FlutterExtension” where you can change sdkversion like minSdkVersion, targetSdkVersion, compileSdkVersion ,ndkVersion.

After Changing desired SdkVersion, save the file.

Video Tutorial

Completer – Handling Future async operation using Flutter Completer

0
Completer in Flutter
Completer in Flutter

In flutter a Completer is a Class that is built to manually complete a future task at some time in future. Basically it’s a way to generate & handle your own Future.

In other words, A ‘Completer’ is an inbuilt class that comes with DART SDK that is basically used to control & manage a ‘Future’ object. A ‘Future’ in flutter we can say it as a value that will be available in future at sometime in time, May be as soon as any asynchronous operation completes.

Video Tutorial on Flutter Completer


When to use completer in flutter

Just Imagine you have ordered a package from a ECommerce Application.

Now you are waiting fro the package to arrive a your door steps.

Then you know that package will be delivered sometime in future or you may know estimate time but not sure exectly when.

In this scenerio, Let’s say Future as Package & Completer as delivery person.

Now, when the delivery person arrives at doorstep the deliver the package, The delivery person make use of Completer to complete the Future i.e The delivery person will mark the package a delivered may be using OTP.


How to use Completer in Flutter App

Syntax of Completer

Completer<dataType> _completer = Completer<dataType>();

Code Example

void main() {
 Completer<String> myCompleter = Completer<String>();

 Future<String> futureValue = myCompleter.future;

 Future.delayed(Duration(seconds: 3),(){
   myCompleter.complete("Hello World");
 });

 futureValue.then((value) {
   print(value);
 });
}

In above code example, First we create a “Completer” object that will result a “String” & then we have created a Future Object by using property i.e. myCompleter.future The futureValue will be listen for myCompleter to complete.

Then, Just for delaying operation we simulate a asynchronous operation using Future.delayed method that sleep for 3 seconds , Then after 2 second the Future.delayed async function will execute & the operation complete, we call ‘completer.complete’ and set a string value “Welcome to Proto Coders Point”, thus this sets a “futureValue” as “Welcome to Proto Coders Point”.

after that we can make use of ‘then’ method to listen for the completion & it print the value on the screen.

Flutter Code Example – How to use Completer in Flutter

In below example, App user can manually complete the completer by clicking on a button.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(title: Text("Completer Example")),
            body: FutureWidget()));
  }
}

class FutureWidget extends StatefulWidget {
  @override
  _FutureWidgetState createState() => _FutureWidgetState();
}

class _FutureWidgetState extends State<FutureWidget> {
  Completer<String> _completer;

  void _handleButtonClick() {
    // Complete the future with the user input
    _completer.complete(_textEditingController.text);
  }

  TextEditingController _textEditingController = TextEditingController();

  @override
  void initState() {
    super.initState();

    // Create the completer when the widget is initialized
    _completer = Completer<String>();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        TextField(
          controller: _textEditingController,
          decoration: InputDecoration(
            hintText: 'Enter some text',
            contentPadding: EdgeInsets.all(10.0),
          ),
        ),
        SizedBox(height: 20),
        ElevatedButton(
            onPressed: _handleButtonClick, child: Text("Complete Future")),
        SizedBox(height: 20),
        FutureBuilder(
          future: _completer.future,
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasData) {
                return Text("Future completed with: ${snapshot.data}");
              } else {
                return Text("Future completed with no data");
              }
            } else {
              return Text("Future not completed yet");
            }
          },
        ),
      ],
    );
  }
}

Programmatically Take Screenshots in Flutter

0
Programmatically take screenshot in flutter

In the digital age, screenshots are an essential component of daily routine  life. They is an efficient part to collect and share the data. that can be very useful in a variety of circumstances. Mobile application screenshots can be used for a variety of the purposes including testing, debugging, documentation etc.. This blog main topic will be how to take a screenshot in a Flutter app.

When testing, debugging, or showcasing the user interface of your Flutter application, the ability to take screenshots is a useful feature. Flutter’s straightforward API makes taking screenshots a breeze. In this blog, we’ll look at how to screenshot in Flutter.

Flutter is a well liked and lightweight framework for building mobile applications . That provides a quick and simple way to create visually appealing, powerful mobile apps for the iOS and Android operating systems. Developers can easily create original interfaces and layouts with Flutter’s high variety of widgets and tools.

How to Programmatically take a Screenshot in flutter

Get started…

Step 1) : Add the Screenshot Package

You must first include the Screenshot package in your project in order to take screenshots in Flutter. In your pubspec.yaml file, open the dependencies section, and then add the following code:

screenshot: ^any

Step 2) : After saving the file launch flutter pub. enter your terminal and start the package download.

flutter pub get

Step 3) : import the file

import 'package:screenshot/screenshot.dart';

Step 4) :Make a screenshot controller

The creation of a Screenshot Controller instance is the next step. You can use this controller to take a screenshot of your widget.

final _screenshotController = ScreenshotController();

Step 5) :Wrap the screenshot of your widget

You must wrap your widget in the Screenshot widget in order to take a screenshot of it. following code should be included in the build method :

Screenshot(
  controller: _screenshotController,
  child: //your widget here,
),

The child property holds the widget that we want to screenshot , and the controller property gives us access to the Screenshot Controller object we previously set up.

Step 6) : Taking a Screenshot

By calling the capture() method on the Screenshot Controller instance, you can finally take a screenshot. Here is an illustration of how to use a floating action button to invoke the capture() method:

FloatingActionButton(
  onPressed: () async {
    final image = await _screenshotController.capture();
    /// do something with the image
  },
  child: Icon(Icons.camera_alt),
),

Step 7) :How to Show or Save a Screenshot

After taking the screenshot you have the option of viewing it or saving it to as a  file. An example of how to show the screenshot that was taken is provided here below :

Image.memory(
  image,
  fit:BoxFit.cover,
),

here,…. you can save screenshot image data  to a file use writeAsBytes function in flutter framework .

final directory = await getApplicationDocumentsDirectory();
final imagePath = '${directory.path}/screenshot.png';

final file = File(imagePath);
await file.writeAsBytes(image);

Step 8) :Reduce the Controller Widget and Screenshot Widget.

It’s critical to remove the Screenshot widget and the Screenshot Controller instance from your code after the screenshot has been taken in order to avoid any performance impact. To accomplish this, set the controller property of the Screenshot widget to null:

Screenshot(
  controller: null,
  child: //your widget here,
),

Additionally, by removing the Screenshot Controller instance:
@override
void dispose() {
///Controller dispose here  
  super.dispose();
}

It’s over now! These easy steps will help you take screenshots of your Flutter app.


screenshot of a widget using RepaintBoundary in Flutter

Video Tutorial

i) : order to take the screenshots of widgets . we will use RepaintBoundary widget as the parent widget. Global key must be used to specify RepaintBoundary.

Visit Flutter RepaintBoundary for more information.

static GlobalKey screen = new GlobalKey();
 RepaintBoundary(
        key: screen,
     child: ChildWidgets(
   )

So that it can be quickly saved in device local storage and transformed into an image bites, the RepaintBoundary widget must then be converted to an image.

Step 1) :Use RepaintBoundary to create widget.

Make widget in your file called MyWidget or any name :

import 'package:flutter/material.dart';

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      child: Container(
        color: Colors.blue,
        width: 200,
        height: 200,
        child: Center(
          child: Text(
            'Hello World!',
            style: TextStyle(
              color: Colors.white,
              fontSize: 30,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
}

This widget has a 300 pixel wide by 300 pixel high container with a white background a font size of 30 bold font weight blue background.

We must first create a GlobalKey object to identify the widget from which we want to take the screenshot. There will also be developed a function called captureScreenshot that will take a screenshot and store it on the device storage.

/// here Define the function to capture the screenshot
  Future<void> captureScreenshot() async {
    try {
      /// Find boundary of the RepaintBoundary widget
      RenderRepaintBoundary boundary =
          _globalKey.currentContext.findRenderObject();
      /// Convert the widget to image
      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      // Convert image to a byte data
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      /// Convert byte data to an Uint8List
      Uint8List pngBytes = byteData.buffer.asUint8List();
      /// Get the application documents directory to save the screenshot widget
      final directory = (await getApplicationDocumentsDirectory()).path;
      /// Create file object and save the screenshot
      File imgFile = File('$directory/screenshot.png');
      await imgFile.writeAsBytes(pngBytes);
      /// Print  message indicating that the screenshot has been taken
      print('Screenshot taken successfully' );
    } catch (e) {
      // Handle the error if there is any
      print(e);
    }
  }

This code creates a Flutter application that use  RepaintBoundary to take screenshot of a widget in flutter . The widget that needs to be captured is wrap in the RepaintBoundary widget .the widget is identified by a global key in flutter.

When the user selects the Take Screenshot button the screenshot is saved to the device local storage .The RepaintBoundary widget boundary is located the captureScreenshot function is invoked and the widget is converted to an image. the image is converted to byte data. byte data is converted to an Uint8List and screenshot is saved in local storage.

For , get this screenshots code , click here…..


Conclusion 👍

I hope you can put this to use.To take a screenshot. use the Flutter screenshot package. With the help of this package we can take screenshot in a specific widget or the entire application screen. In this blog post, we will look at using this package to take screenshot in Flutter application. This example code can be changed to suit your requirements.

Thanks for reading this article……

Have a beautiful day…..

How to use the Value Notifier in flutter.

0
flutter value Notifier

ValueNotifier is a unique subclass of Changenotifier that can hold a single value and alert widgets that are listening to it whenever that value changes. ValueNotifier extends Changenotifier.

ValueNotifier offers an easy and effective way to manage and update state in your application. making it a useful and lightweight tool for developing reactive data sources in Flutter.

When you need to update the UI due to changes in a value. ValueNotifier comes in handy. You can use a ValueNotifier for instance to keep track of changes to the value of a text field in a user interface . so that other UI elements can be updated to reflect the new value.

The main benefit of using a ValueNotifier over state management alternatives like setState or streams is that it is portable and simple to operate. It does not necessitate the creation of intricate streams and stream controllers, nor is it as resource-intensive as setState for straightforward use cases.

What is ValueNotifier?

Let’s first define ValueNotifier so that we can proceed to the specifics of how to use it in Flutter. A straightforward observable data model can be made using the class called ValueNotifier. It is a simplified version of the ChangeNotifier class, which forms the backbone of the reactive programming style used by Flutter. ValueNotifier has a single property named value that stores the model’s current value. The model alerts its listeners whenever its value changes. Due to this, it is simple to develop reactive Flutter applications, in which the UI is updated whenever the data changes.

How can ValueNotifier be used?

It’s very easy to use ValueNotifier in Flutter. You can create a ValueNotifier by providing it with an initial value. For instance , you  follow these steps to create a ValueNotifier that stores an integer value:

// syntax --> ValueNotifier<dataType> myValueNotifier = ValueNotifier<dataType>(value);

// Example :
ValueNotifier<int> myValueNotifier = ValueNotifier<int>(0);

In this example, we making a ValueNotifier that stores the value 0 as an integer.

When you have a use  ValueNotifier you can use the value property to read and modify its value. For instance you can follow these steps to read the value of the ValueNotifier:

Read the value of the ValueNotifier Object:

int currentValue = myValueNotifier.value;

ValueNotifier value property’s value can be modify by assigning  new value . For example the following steps can be used to update the ValueNotifier value to 100 :

myValueNotifier.value = 100;

The ValueNotifier notifier listeners updated whenever value is updated or changed . The addListener method can be used keep track of changes in ValueNotifier variable.

myValueNotifier.addListener(() {
  print('Value changed to ${myValueNotifier.value}');
});

In this example, we’re extending the myValueNotifier with a listener that prints a message whenever its value changes.

To build a basic data model that can be used to update the user interface, ValueNotifier is frequently used in Flutter widgets. ValueNotifier can be used in widgets by simply creating a new instance of it and passing it to the child widgets as necessary. Here’s a good example:

using ValueNotifier


class ValueNotifierExample extends StatelessWidget {
  ValueNotifierExample({Key? key}) : super(key: key);
  final ValueNotifier<int> myValueNotifier = ValueNotifier<int>(42);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(backgroundColor: Colors.blue.shade900,title: const Text("Value notifier implement")),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Value: ${myValueNotifier.value}'),
          ElevatedButton(
            onPressed: () {
              myValueNotifier.value += 1;
            },
            child: const Text('Increment Value'),
          ),
        ],
      ),
    );
  }
}

Here is an example showing , how to create a ListView in Flutter using the ValueNotifier builder set:

import 'package:flutter/material.dart';

class ListViewValueNotifier extends StatefulWidget {
  const ListViewValueNotifier({super.key});

  @override
  _ListViewValueNotifierState createState() => _ListViewValueNotifierState();
}

class _ListViewValueNotifierState extends State<ListViewValueNotifier> {
  ValueNotifier<int> selectedIndex = ValueNotifier<int>(0);

  List<String> items = [
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue.shade900,
        title: const Text("ListView with ValueNotifier"),
      ),
      body: ValueListenableBuilder(
        valueListenable: selectedIndex,
        builder: (BuildContext context, int index, Widget? child) {
          return ListView.builder(
            itemCount: items.length,
            itemBuilder: (BuildContext context, int i) {
              return ListTile(
                title: Text(items[i]),
                selected: i == index,
                onTap: () {
                  selectedIndex.value = i;
                },
              );
            },
          );
        },
      ),
    );
  }
}

Conclusion 👍

ValueNotifier is a component of Flutter’s core Reactive Programming Model, which enables the creation of responsive and effective user interfaces. A ValueNotifier is a simple class that enables the development of reactive data sources that alert listeners when their values change.

ValueNotifier offers an easy and effective way to manage and update state in your application, making it a useful and lightweight tool for developing reactive data sources in Flutter.

Thanks for reading this article 💙…..

Have a beautiful day…..

Recommended Book