颤抖着如何正确地将数据传递给StatefulWidget

时间:2020-06-07 13:52:20

标签: flutter

我的目标是编写一个Flutter应用程序,用于管理课程和分配给课程的学生。我有一个Homeview,可以在其中点击相应的按钮来选择课程。点击按钮后,将显示CourseViewCourseView是所选课程的概述,您可以在其中选择座位计划和学生名单。

学生和课程存储在sqlite数据库中。

我正在将用户点击的过程作为路由参数传递给CourseView。我想为座位计划创建标签(=小部件列表),并在initState()方法内创建学生列表。因此,在加载所有分配给该课程的学生之前,我调用了getStudentsForCourse()函数。

class _CourseViewState extends State<CourseView> {
  DBHelper dbHelper;
  Future<List<Student>> studentsListFuture;
  List<Widget> tabs = [];

  @override
  initState() {
    super.initState();
    dbHelper = DBHelper.dbHelper;

    // now load all the students for this course
    studentsListFuture = dbHelper.getStudentsForCourse(currentCourse);
    // and then add the seating plan
    tabs.add(
      // seating plan view
    );
    // ...and the list
    tabs.add(
      // students list view
    );
  }

  @override
  Widget build(BuildContext context) {
    // only here I can retrieve the arguments of the route
    final Course currentCourse = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text(course.name),
      ),
       body: tabs[currentIndex],
       bottomNavigationBar: BottomNavigationBar(
         //navigate through the tabs
       ),
    );
  }

}

这行不通,因为致电getStudentsForCourse()时我还没有课程。我该如何解决?我认为我的做法不正确。

编辑:@MSARKrish建议的内容对我有用。但是我正在使用MaterialApp中定义的路由:

return MaterialApp(
      title: 'title',
      initialRoute: '/',
      routes: {
        '/': (context) => HomeView(),
        '/CourseView': (context) => CourseView(),
      },
    );

我可以保留路由并将作为参数传递给CourseView的构造函数吗?

1 个答案:

答案 0 :(得分:1)

您正在将用户选择的课程传递给该“课程小部件”。 您可以在状态类中将该变量用作widget.course

示例: 您可以像这样通过selectedCourse:

Navigator.push(context,MaterialPageRoute(builder: (context){return CourseView(selectedCourse: course);})); 

您会得到这样的消息:

class CourseView extends StatefulWidget {

 final String selectedCourse;
 CourseView({this.selectedCourse});
 @override
 _CourseViewState createState() => _CourseViewState();
 }

 class _CourseViewState extends State<CourseView> {

  void initState() {
    print(widget.selectedCourse);

    }

   @override
   Widget build(BuildContext context) {
     return Scaffold();
 }
 }