所以我正在嘗試創建一個應用程式,您可以在其中編輯輸入欄位,當 TextFields(輸入)中的值發生變化時,它會為您計算一些值。為了實作這一點,我嘗試使用提供者來保存它們的值以及設定器和獲取器,但是每當使用設定器時,一切都會凍結。
從頂部開始,我的 MaterialApp 是這樣設定的,使用 MultiProvider 小部件并添加提供者(雖然目前只有一個):
return MultiProvider(
providers: [
ChangeNotifierProvider<CalculationService>(create: (_) => calculationService),
],
child: Builder(
builder: (context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Palette.primary,
scaffoldBackgroundColor: const Color(0xFFF8F9FA),
),
home: RootScreen(),
);
},
),
);
然后,我的“RootScreen”獲得了包含值以及 getter 和 setter 的calculationService(set areaInMeterSquared(int state)我相信這是重要的部分):
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();
}
}
TextField(s) 看起來像這樣:
TextFormField(
initialValue: calculationService.areaInMeterSquared.toString(),
onChanged: (text) {
calculationService.areaInMeterSquared = int.parse(text);
},
),
謝謝你的幫助 :)
編輯:我得到的錯誤是[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Stack Overflow
uj5u.com熱心網友回復:
在 CalculationService 中使用這個
int areaInMeterSquared = 0;
int get getAreaInMeterSquared => areaInMeterSquared;
set setAreaInMeterSquared(int state) {
sharedPreferences.setInt(areaInMeterSquaredKey, state);
areaInMeterSquared = state;
notifyListeners();
}
文本表單欄位應該是這樣的
TextFormField(
initialValue: calculationService.getAreaInMeterSquared.toString(),
onChanged: (text) {
if(int.tryParse(text) > 0)
{
calculationService.setAreaInMeterSquared(int.parse(text));
}
},
),
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/489285.html
