Muhammad Tameem Rafay
Muhammad Tameem Rafay

Reputation: 11

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

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

}

Upvotes: 0

Views: 7338

Answers (2)

Mohamad Assem Nasser
Mohamad Assem Nasser

Reputation: 1109

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

Upvotes: 4

Quyền Phạm Danh
Quyền Phạm Danh

Reputation: 29

Solution for your code:

var temp2 = showDetailOfUniversity(UniversityId: university_id);

var temp = temp2.UniversityId; //this will return university_id

Upvotes: 0

Related Questions