如何从一类到另一类中的变量访问变量

时间:2019-11-05 18:53:40

标签: flutter flutter-test

我要访问_HomePageState类中的变量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

}

2 个答案:

答案 0 :(得分:1)

这里的问题是您创建了showDetailOfUniversity的另一个实例,该实例的成员具有另一个值。您尚未初始化String UniversityId,因此在您进行设置之前,其值为null。

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

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

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

答案 1 :(得分:0)

您的代码的解决方案:

var temp2 = showDetailOfUniversity(UniversityId: university_id);

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