Simran Aswani
Simran Aswani

Reputation: 1316

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

I have a button I want to disable after incrementing my counter. This is the method I'm using to increment my counter:

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

Inside initState:

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

I have a button and I've called these methods on the onTap if the buttons:

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);
  }

When I call this method it shows me the following error:

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

Upvotes: 0

Views: 1632

Answers (3)

Crazy Lazy Cat
Crazy Lazy Cat

Reputation: 15053

Try this,

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

Upvotes: 1

J. S.
J. S.

Reputation: 9615

This modification of your original code will do exactly what you are asking for:

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++;
  });
}

The rest of your code doesn't need modification with the exception of the fact that you don't need to save into SharedPreferences if your button is disabled. You can just validate it against the value.

Upvotes: 1

Aamil Silawat
Aamil Silawat

Reputation: 8229

int adCounter=0; (initialize value first whatever you want)

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

Upvotes: 1

Related Questions