Home > OS >  How to update variable from inside a function?
How to update variable from inside a function?

Time:06-26

I want to change the value of RowIndex from _getAttendence

class Attendence extends StatefulWidget {
  const Attendence({Key? key}) : super(key: key);

  @override
  State<Attendence> createState() => _AttendenceState();
}

class _AttendenceState extends State<Attendence> {
  String RowIndex = "0";
Widget build(BuildContext context){...}
 _getAttendence(String KEY, String RowIndex) async {
          RowIndex = "50";
   }
}

CodePudding user response:

First option is to create a global variable inside the class like this:

// 'a' can also be placed here :)
class MyPage extends StatefulWidget {
  const MyPage({Key? key}) : super(key: key);

  @override
  State<MyPage> createState() => _MyPageState();
}

// this is a global variable. It has no colors. (see image)
double a = 20.0;
/*
  now, wherever you import the file containing the class 'MyPage',
  you can use this variable!
 */

class _MyPageState extends State<MyPage> {
  
  // this is a local variable. It has a purple color. (see image)
  double b = 10.0;
  
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

picture showing the colors

Second option is to create a dart file, let's call it globals.dart. Then, in this file define your variables, double a = 10.0; And then in your other dart files you can either import it as before and use the variables or you can use this: in your other files use: import: 'globals.dart' as globals; and then in your file you can use: globals.a = 20.0; inside a setState(()=>{});. Don't forget to setState above as well :)

CodePudding user response:

RowIndex is not global, it's class wide, it's nested in your State object, if you want to make it global, put it outside the class tag, you could do this

    @override
    State<Attendence> createState() => _AttendenceState();
  }

    class _AttendenceState extends State<Attendence> {
  String RowIndex = "0";

  _getAttendence(String KEY, String RowIndex) async {
    for (var q in (aList as List)) {
      AttendenceList innerAttendence = AttendenceList(
          q["RowIndex"],
          q["Id"],
          q["InText"],
          q["OutText"],
          q["InDate"],
          q["Duration"],
          q["DateBGColorHEX"],
          q["InColorHEX"],
          q["OutColorHEX"],
          q["DurationColorHEX"]);
      FetchList.add(innerAttendence);
    }
    setState(() {
      RowIndex = FetchList[FetchList.length - 1].RowIndex.toString();
    });
  }
  
  @override
  void initState() {
    if (controller.position.maxScrollExtent == controller.offset) {
      _getAttendence(KEY!, RowIndex);
    }
    super.initState();
  }
}
  • Related