dimanche 20 janvier 2019

Flutter- How to hold data in memory throughout app lifetime in flutter?

I wish to know, how to hold data which I am using in multiple screens. Should we use the Singleton design pattern in a flutter?

Suppose I made login module using BLoC pattern like here https://github.com/adamjohnlea/Flutter-Login-With-BLoC-Pattern.

Now if for every request to the server, I need an email and password to be sent.

Provider code:

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

class Provider extends InheritedWidget {

  final bloc = new Bloc();

  Provider({Key key, Widget child})
    : super(key: key, child: child);

  bool updateShouldNotify(_) => true;

  static Bloc of(BuildContext context) {
    return (context.inheritFromWidgetOfExactType(Provider) as Provider).bloc;
  }

}

Bloc code:

import 'validators.dart';
import 'package:rxdart/rxdart.dart';

class Bloc extends Object with Validators {
  final _email = BehaviorSubject<String>();
  final _password = BehaviorSubject<String>();

  // retrieve data from stream
  Stream<String> get email    => _email.stream.transform(validateEmail);
  Stream<String> get password => _password.stream.transform(validatePassword);
  Stream<bool>   get submitValid => Observable.combineLatest2(email, password, (e, p) => true);

  // add data to stream
  Function(String) get changeEmail    => _email.sink.add;
  Function(String) get changePassword => _password.sink.add;

  submit() {
    final validEmail    = _email.value;
    final validPassword = _password.value;

    print('$validEmail and $validPassword');
  }

  dispose() {
    _email.close();
    _password.close();
  }
}

1. Should I make singleton class eg. AccountManager, where I will store the user details and get details wherever I need? or Should I use below Provider to get the email & password anywhere in the app?

2. Is it recommended to hold data in Singleton classes?

Aucun commentaire:

Enregistrer un commentaire