Search code examples
flutterdartstate-management

Flutter - Is there any way to change variable value without using setState() or notifyListeners()


I want to ask if there is any other way than using SetState() or notifyListener() to change the value of bool. Because using setState() or notifyListener() crashes app for some seconds. actually i m using NotificationListener to change the value of bool on user scroll. Please help


Solution

  • use stream.it is like a pipe you add value from a side (Sink) and recieve it on the other side (Stream).i will try to explain it:

      //make a stream controller
      StreamController<bool> valueController = StreamController();
      
      //this will listen to every new value you add
      Stream valueOutput = valueController.stream;
    
      //you can add new values throw the sink
       Sink valueInput = valueController.sink;
    

    so when you want to add a value to the stream just call

    valueInput.add(true);//add whatever booleon value you want
    

    and then recieve it by calling

     valueOutput.listen((value) {
       //this function will be invoked every time you add a new value.
     });
    

    or you can add StreamBuilder if you want to rebuild a specific widget based on that boolean value

    StreamBuilder(
          stream: valueOutput,
          builder: (context,snapshot) {
    
           bool value = snapshot.data;
           log(value.toString());//true or false
    
           return yourWidget();
        })
    

    i hope i explained it well, good luck with your problem.

    i think when you use setState it rebuilds the entire screen and if you are using scroll controller to listen to user`s scroll then the screen will rebuild every pixel user scrolls so that is a lot of rendering. maybe share some code snippet of your code so we can help.