如何在 flutter 中从一个 class 访问变量到另一个

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

我想访问 _HomePageState

的 class 中的变量 UniversityId
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

}

您的代码的解决方案:

var temp2 = showDetailOfUniversity(UniversityId: university_id);

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

这里的问题是您创建了 showDetailOfUniversity 的另一个实例,它的成员将具有另一个值。您没有初始化 String UniversityId 所以它的值为 null 直到您设置它。

因此,当您在 temp 中调用 showDetailOfUniversity() 时,此实例中 String UniversityId 的值为空,因为在此特定实例中未给出任何值。

您可以像这样在 StatefulWidget 的构造函数中传递 String UniversityId

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