Geoff
Geoff

Reputation: 6629

Flutter execute a function when a value of a variable changes

Am new to flutter and in my widget i have an integer that i would like to execute a function when its value is changed.

  import 'package:flutter/material.dart';
   
  class TestPageWidget extends StatefulWidget {
    const TestPageWidget({ Key? key }) : super(key: key);

    @override
   _TestPageWidgetState createState() => _TestPageWidgetState();
    }

  class _TestPageWidgetState extends State<TestPageWidget> {

   int myItem = 1; //listen changes to this and execute a function


   @override
   void initState() {
    super.initState();
   
    //change myItem value after 3 seconds
     Future.delayed(Duration(seconds: 3), () {
        myItem = 3;
    });
  }
   
  //something like this. Am not sure how i can listen for the change
  ValueNotifier(value) {
      print('Value as now changed'); //expected this to show after delay of 3 seconds
  }
}

AM changing the value in the initstate and using ValueNotifier to check if it has changed but it never prints even after change. Is there a way i can watch for myItem value and execute a function if the value changes.

Upvotes: 4

Views: 6426

Answers (1)

rosh-dev851
rosh-dev851

Reputation: 564

According to your requirement there is simple solution without ValueNotifier. ValueNotifier is more suitable when you want to refresh a widget when a value changes

class _TestPageWidgetState extends State<TestPageWidget> {
  int myItem = 0; //listen changes to this and execute a function

  void setItem(int itemValue) {
    this.myItem = itemValue;
    this.itemChanged();
  }

  @override
  void initState() {
    super.initState();

    //change myItem value after 3 seconds
    Future.delayed(Duration(seconds: 3), () {
      setItem(3);
    });
  }

  void itemChanged() {
    print(this.myItem);
  }
}

Upvotes: 1

Related Questions