Home > Enterprise >  How to update data in flutter
How to update data in flutter

Time:02-05

I use mvvm architecture and I want to update my data in the view model without the need to call rebuild methods, use stream or future builders, and use any external packages. Overall I want to listen to changes not only on a specific variable but on the entire class instead

I tried using inherited widget but this doesn't help

CodePudding user response:

for that, you should any os flutter state manager. You can use Bloc but for MVVM architecture you can use Getx. Try to learn Getx .obs and GetxBuilder to listen to new changes and update your application according to them.

Package : https://pub.dev/packages/get

CodePudding user response:

you can use Provider as a state management in your project to make all the data that you need alive in your project:

step 1) please add provider: ^6.0.5 (or any version that is compatible) in your pubspec.yaml and call flutter pub get.

step 2) now you should create a provider class to make all the variables that you want to use everywhere, alive. please create a dart file as below:

import 'package:flutter/material.dart';

class ExpampleClassProvider extends ChangeNotifier {

String? _yourData;

void setYourData(String? newData){
_yourData = newData;
 notifyListeners();
}

String? get yourData => _yourData;

}

as you see when _yourData is changed, it tells you and you can use this data where ever you want by providing ExpampleClass,even you can set a data in your first screen and use that data in the last screen without passing data step page by step.

step 3) you should add the provider to main.dart:

MultiProvider(
      providers: [
// you are adding your provider
        ListenableProvider.value(value: ExpampleClassProvider()),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        home: ...........
      ),
    );

now you can use it where ever you want:

Provider.of<ExpampleClass>(context, listen: false).yourData;

and even you can use that data in your widgets like this by using Consumer everywhere you want:

Consumer<ExpampleClassProvider>(
        builder: (context, exampleClassProvider ,snapshot) {
          return Text(exampleClassProvider!.yourData);
        }
      )

read the Provider document carefully.

happy coding...

  • Related