簡體   English   中英

如何在 Flutter 中增加計數器並禁用按鈕?

[英]How do I increment a counter and disable a button in Flutter?

我有一個按鈕,我想在增加計數器后禁用它。 這是我用來增加計數器的方法:

void incrementAdCounter() async {
    setState(() {
      adCounter++;
      if (adCounter == 2 || adCounter > 2) {
        isAdButtonDisabled = true;
      }
      setAdCounter();
      print(adCounter);
    });
  }

內部初始化狀態:

void initButtons() {
    isAdButtonDisabled = false;
    adCounter = 0
}

我有一個按鈕,如果按鈕:

void getCounters() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  adCounter = prefs.getInt('adCounter');
  isAdButtonDisabled = prefs.getBool('isAdButtonDisabled');
}
setAdCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt('adCounter', adCounter);
    prefs.setBool('isAdButtonDisabled', isAdButtonDisabled);
  }

當我調用此方法時,它顯示以下錯誤:

Unhandled Exception: NoSuchMethodError: The method '+' was called on null.
E/flutter (13166): Receiver: null

int廣告計數器=0; (無論你想要什么,首先初始化值)

void incrementAdCounter() async {
    setState(() {
      adCounter++;
      if (adCounter == 2 || adCounter > 2) {
        isAdButtonDisabled = true;
      }
      setAdCounter();
      print(adCounter);
    });
  }

對原始代碼的這種修改將完全滿足您的要求:

int adCounter = 0;

@override
Widget build(BuildContext context) {
  return Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text(adCounter.toString()),
        RaisedButton(
          onPressed: adCounter >= 2 ? null : incrementAdCounter,
          child: Text('Increment'),
        ),
      ],
    )
  );
}

void incrementAdCounter() {
  setState(() {
    adCounter++;
  });
}

您的其余代碼不需要修改,但如果您的按鈕被禁用則您不需要保存到 SharedPreferences。 您可以根據值驗證它。

試試這個,

void getCounters() async { 
  SharedPreferences prefs = await SharedPreferences.getInstance();
  adCounter = prefs.getInt('adCounter') ?? 0;
  isAdButtonDisabled = prefs.getBool('isAdButtonDisabled'); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM