setState vs notifyListeners vs Obs

Flutter

Comparative analysis of setState, notifyListeners, and obs in Flutter

Flutter Tutorial

Introduction

Flutter

Cross Platform

MVVM vs MVC vs MVP

Flutter Framework

Flutter Benefits

Flutter Comparison

Install Flutter in Win/Linux/Mac

Android Studio vs VsCode

Android Setup

VS Code Setup

VS Code Plugins

Android Studio Plugins

Flutter Widgets:

Flutter Basic Template

Flutter Commands

Top 10 Popular widgets

Flutter Stateless vs Stateful

Type of Widgets

Flutter Text widget

Flutter Text style

Textfield vs TextFormField

Flutter Scaffold

Flutter Container & SizedBox

Flutter Row & Column

Flutter Buttons

Flutter Stack

Flutter Forms

Flutter AlertDialog

Flutter Icons

Flutter Images

Flutter Drawer

Flutter ListView

Flutter GridView

Flutter Toast

Flutter Checkbox

Flutter Radio Button

Flutter Progress Bar

Flutter Tooltip

Flutter Slider

Flutter Table

Flutter SnackBar

Shimmer in Flutter

Bottom Navigation Bar in Flutter

Gesture Detector in Flutter

Error Handling in Flutter

DropDown in Flutter

Flutter Toggle

Auto Close Keyboard in Flutter

Screen size handling in Flutter

Flutter REST API

Flutter http

Flutter dio

dio vs http

Flutter Advance

Custom widget in Flutter

Flutter Navigator

Read Json in Flutter

Generate Excel in Flutter

Multiple Widgets in Flutter

Bottom sheet in Flutter

Copy to Clipboard in Flutter

Tab bar in Flutter

Code Editor in Flutter

Youtube Player in Flutter

Flutter App Development Tips

Flutter App version Update

Flutter Copy Text in App

Flutter Handle Null Value

Flutter Splash Screen

Flutter Disposable

Notification Listener

Flutter Switch Cases

Flutter Slivers

Flutter Custom App bar

Databinding in Flutter

Flutter Cards

Wrap vs Builder vs OverBarFlow

Flutter App Upgrade

GoogleMap vs FlutterMap

Circular progress contain Icon

DropDown Timer in Flutter

Flutter State management Comparison

Flutter vs Other Framework

Flutter Mixin

Passing values in Dart Files

WorkManager in Flutter

Flutter Database

Flutter Store Data

Suitable DB for Flutter

Backend for Flutter

SharedPreferences in Flutter

Flutter Token Expired Handling

Flutter Provider

Flutter Provider Tutorial

Flutter GetX

Flutter GetX tutorial

Flutter with Native

Flutter FFI

Flutter Testing

Flutter Tips

Best Practices

Reduce Flutter Screens

Tips to make app smart

Optimize App

Handle Multiple Pages

Interview Questions

Flutter 100 Interview Questions

Provider Interview Questions

GetX Interview Questions

BLoC Interview Questions

In flutter setState vs notifyListeners vs obs all are used to show updated value on screen without refresh or clicking button. setstate used in stateful widget and no additional package required for this, notifyListeners comes with provider package and obs is comes with GetX package. These methods are very popular and used in every Flutter applications. In short words these method auto refresh the variable or and datatype values

setState vs notifyListeners vs Obs
CriteriasetState (Flutter)notifyListeners (Provider)obs (Getx)
Ease of UseBy default available in Flutter framework, used in stateful widgetRequires additional package provider, extending
ChangeNotifier and managing listeners (see below example)
use obs modifier on variables , variable update automatically (see below example)
FlexibilityStandard Flutter state management approachProvides a clear structure for managing state changesLightweight, reactive, and flexible
Dependency Managementno external dependenciesProvider library, adds some dependenciesGetx library, adds minimal dependencies

setState Example (Flutter)


import 'package:flutter/material.dart';

class CounterApp extends StatefulWidget {
  @override
  _CounterAppState createState() => _CounterAppState();
}

class _CounterAppState extends State<CounterApp> {
  int _counter = 0;

  void _incrementCounter() {
//Here setState update _counter variable automatically
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Counter Value:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
// When user press _incrementCounter, setState update _counter variable automatically
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: CounterApp(),
  ));
}

Provider

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

class CounterModel extends ChangeNotifier {
  int _counter = 0;

  int get counter => _counter;

  void incrementCounter() {
//// Here notifyListener update _counter variable automatically
    _counter++;
    notifyListeners();
  }
}

class CounterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => CounterModel(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text('Counter App'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('Counter Value:'),
                Consumer<CounterModel>(
                  builder: (context, counterModel, child) {
                    return Text(
                      '${counterModel.counter}',
                      style: Theme.of(context).textTheme.headline4,
                    );
                  },
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
//// When user press _incrementCounter, Provider update _counter variable automatically
              Provider.of<CounterModel>(context, listen: false).incrementCounter();
            },
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        ),
      ),
    );
  }
}

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

obs Example (Getx)

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

class CounterController extends GetxController {
//Here in this counter varaibale is obs
  var counter = 0.obs;

  void incrementCounter() {
    counter++;
  }
}

class CounterApp extends StatelessWidget {
  final CounterController counterController = Get.put(CounterController());

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Counter App'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Counter Value:'),
//// When user press _incrementCounter, Obx update _counter variable automatically
              Obx(() {
                return Text(
                  '${counterController.counter}',
                  style: Theme.of(context).textTheme.headline4,
                );
              }),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
//Increment function
            counterController.incrementCounter();
          },
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

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

If you face any issue, please comment below, we will reply soon

Leave a Reply

Your email address will not be published. Required fields are marked *

web_horizontal
About Us ♢ Disclaimer ♢ Privacy Policy ♢ Terms & Conditions ♢ Contact Us

Copyright © 2023 ResearchThinker.com. All rights reserved.