Created
April 9, 2022 21:29
-
-
Save riscait/22487871564473a6a8867dd45aff93cd to your computer and use it in GitHub Desktop.
Use "getter" or "late final" or "object injection" ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:riverpod/riverpod.dart'; | |
final stateProvider = StateProvider((_) => 1); | |
final getterClassProvider = Provider((ref) => GetterClass(ref.read)); | |
class GetterClass { | |
GetterClass(this._read) { | |
print('Construct GetterClass'); | |
} | |
final Reader _read; | |
int get stateValue => _read(stateProvider); | |
} | |
final lateFinalClassProvider = Provider((ref) => LateFinalClass(ref.read)); | |
class LateFinalClass { | |
LateFinalClass(this._read) { | |
print('Construct LateFinalClass'); | |
} | |
final Reader _read; | |
late final stateValue = _read(stateProvider); | |
} | |
final injectionClassProvider = Provider((ref) => InjectionClass(ref.watch(stateProvider))); | |
class InjectionClass { | |
InjectionClass(this.stateValue) { | |
print('Construct InjectionClass'); | |
} | |
final int stateValue; | |
} | |
void main() { | |
final container = ProviderContainer(); | |
print('# Read providers'); | |
final getterClass = container.read(getterClassProvider); | |
final lateFinalClass = container.read(lateFinalClassProvider); | |
final injectionClass = container.read(injectionClassProvider); | |
print('-----'); | |
print('# Retrieve value'); | |
print('GetterClass.stateValue: ${getterClass.stateValue}'); | |
print('LateFinalClass.stateValue: ${lateFinalClass.stateValue}'); | |
print('InjectionClass.stateValue: ${injectionClass.stateValue}'); | |
print('-----'); | |
print('# Update stateProvider.state from 1 to 2'); | |
container.read(stateProvider.notifier).state = 2; | |
print('-----'); | |
print('# Re-retrieve value'); | |
print('GetterClass.stateValue: ${getterClass.stateValue} <- changed'); | |
print('LateFinalClass.stateValue: ${lateFinalClass.stateValue}'); | |
print('InjectionClass.stateValue: ${injectionClass.stateValue}'); | |
print('-----'); | |
print('# Re-read providers'); | |
final getterClass2 = container.read(getterClassProvider); | |
final lateFinalClass2 = container.read(lateFinalClassProvider); | |
final injectionClass2 = container.read(injectionClassProvider); | |
print('-----'); | |
print('# Retrieve value from newly readed providers'); | |
print('GetterClass.stateValue: ${getterClass2.stateValue}'); | |
print('LateFinalClass.stateValue: ${lateFinalClass2.stateValue}'); | |
print('InjectionClass.stateValue: ${injectionClass2.stateValue} <- changed'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment