So I'm trying to create an app where you can edit input fields, and it will calculate some values for you when the values in the TextFields (inputs) changes. To achieve this I'm trying to use a provider to hold the values and setters and getters for them, but whenever the setter is used everything freezez up.
From the top my MaterialApp is set up like this using the MultiProvider widget and adding providers (currently only one though):
return MultiProvider(
providers: [
ChangeNotifierProvider<CalculationService>(create: (_) => calculationService),
],
child: Builder(
builder: (context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Palette.primary,
scaffoldBackgroundColor: const Color(0xFFF8F9FA),
),
home: RootScreen(),
);
},
),
);
My "RootScreen" then gets the calculationService which holds the values and getters and setters (the set areaInMeterSquared(int state)
is the important part here i believe):
class CalculationService with ChangeNotifier {
late final SharedPreferences sharedPreferences;
// Inputs
final int _areaInMeterSquared = 0;
final int _basicRentForUnit = 0;
final int _installmentsPerYear = 0;
final int _tenantCustomizations = 0;
final int _technicalUpgrades = 0;
CalculationService(this.sharedPreferences);
final double rateOfReturn = 0.02;
final double inflation = 0.05;
final int tenantCustomizationYears = 5;
final int technicalUpgradeYears = 20;
int get areaInMeterSquared => _areaInMeterSquared;
int get basicRentForUnit => _basicRentForUnit;
int get installmentsPerYear => _installmentsPerYear;
int get tenantCustomizations => _tenantCustomizations;
int get technicalUpgrades => _technicalUpgrades;
set areaInMeterSquared(int state) {
sharedPreferences.setInt(areaInMeterSquaredKey, state);
areaInMeterSquared = state;
notifyListeners();
}
}
And the TextField(s) looks like this:
TextFormField(
initialValue: calculationService.areaInMeterSquared.toString(),
onChanged: (text) {
calculationService.areaInMeterSquared = int.parse(text);
},
),
Thanks for any help :)
EDIT: The error i get is [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Stack Overflow
CodePudding user response:
In CalculationService use this
int areaInMeterSquared = 0;
int get getAreaInMeterSquared => areaInMeterSquared;
set setAreaInMeterSquared(int state) {
sharedPreferences.setInt(areaInMeterSquaredKey, state);
areaInMeterSquared = state;
notifyListeners();
}
The text form field should be like this
TextFormField(
initialValue: calculationService.getAreaInMeterSquared.toString(),
onChanged: (text) {
if(int.tryParse(text) > 0)
{
calculationService.setAreaInMeterSquared(int.parse(text));
}
},
),