How to access the variable from one class to other in flutter

Issue

I want to access the variable UniversityId in the class of _HomePageState

class showDetailOfUniversity extends StatelessWidget {

   final String UniversityId;

  showDetailOfUniversity({Key key, @required this.UniversityId}) : super(key: 
      key);

  @override

  Widget build(BuildContext context)
 {

    return  (
      HomePage()
    );

  }
}

class HomePage extends StatefulWidget {

  @override

  _HomePageState createState() => _HomePageState();

}

class _HomePageState extends State<HomePage> {

//   
    var temp2 = showDetailOfUniversity();

   var temp = temp2.getUniversityId;

  /// here i want to access the code but failed

}

Solution

The problem here is that you created another instance of showDetailOfUniversity that will have another values for its members. You did not initialize String UniversityId so its value is null untill you set it.

So when you called showDetailOfUniversity() in temp, the value of String UniversityId in this instance is null since there was no value given in this particular instance.

You can pass the String UniversityId in the constructor of the StatefulWidget like this:

class ShowDetailOfUniversity extends StatelessWidget {
  final String universityId;

  ShowDetailOfUniversity({Key key, @required this.universityId})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return HomePage(universityId: universityId);
  }
}

class HomePage extends StatefulWidget {
  final String universityId;

  const HomePage({Key key, this.universityId}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  var universityId;

  @override
  void initState() {
    super.initState();
    universityId = widget.universityId;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Text(universityId);
  }
}

Answered By – Mohamad Assem Nasser

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.