Flutter:通过BottomNavigationBar中的页面解析数据。错误:只能在初始化程序中访问静态成员

时间:2019-06-27 18:40:53

标签: parsing flutter flutter-layout bottomnavigationview

我有一个BottomNavigationbar,我想通过参数解析数据!我收到错误消息:在初始化程序中只能访问静态成员。

class _LoggedInStudentState extends State<LoggedInStudent> {

final String bearer;
final String username;
_LoggedInStudentState(this.bearer, this.username);

int _selectedPage = 0;

List<Widget> _pageOptions = [
  StudentHomePage(bearer, username),
  StudentProjectPage(),
  StudentStudyplanPage()
];

@override
Widget build(BuildContext context) {
 return Scaffold(
  endDrawer: Drawer(),
  appBar: AppBar(
    automaticallyImplyLeading: false,
    backgroundColor: Colors.white,
    iconTheme: IconThemeData(color: Colors.black54),
    elevation: 0,
  ),
  body: _pageOptions[_selectedPage],
  bottomNavigationBar: BottomNavigationBar(
    currentIndex: _selectedPage,
    onTap: (int index) {
      setState(() {
        _selectedPage = index;
      });
    },
      items: [
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text('Hem')
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.school),
          title: Text("Skolprojekt")
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.check_circle_outline),
          title: Text("Studieplaner")
        ),
      ],
  ),
);

} }

有关如何设置首页的更多信息:与您一样。我可以确定最终的String承载者和最终的String用户名。

class _StudentHomePageState extends State<StudentHomePage> {

final String bearer;
final String username;
_StudentHomePageState(this.bearer, this.username);

@override
Widget build(BuildContext context) {
  return Container(
  child: ListView(
    children: <Widget>[

      Container(
          margin: EdgeInsets.only(left: 20),
          alignment: Alignment.centerLeft,
          child: Column(
            children: <Widget>[
              Container(child: Text('Välkommen Tillbaka', style: TextStyle(fontSize: 30, fontWeight: FontWeight.w600),), alignment: Alignment.centerLeft,),
              Container(child: Text('${username.toUpperCase()[0]}${username.substring(1)}!', style: TextStyle(fontSize: 30, fontWeight: FontWeight.w600),), alignment: Alignment.centerLeft,),

            ],
          )
      )

    ],
  ),
);
}
}

这是一个问题,因为页面位于数组中吗?当我将navigator.push到页面时,这始终有效。如果有人有溶液。随时提供帮助:)

1 个答案:

答案 0 :(得分:0)

问题在于,当您尝试构建_pageOptions时,由于定义了对象时传递了承载和用户名,因此未定义承载和用户名。如果这些变量是“常量”,则只需声明为静态变量即可。

由于在这种情况下,您需要使用动态数据来构建页面选项,因此您需要在构建_LoggedInStudentState之后设置pageOptions,因为此时您已经拥有了载体和用户名。

尝试这样的事情:

class _LoggedInStudentState extends State<LoggedInStudent> {

final String bearer;
final String username;
final List<Widget> _pageOptions;
_LoggedInStudentState(this.bearer, this.username)
  : _pageOptions = [
      StudentHomePage(bearer, username),
      StudentProjectPage(),
      StudentStudyplanPage()
    ];

int _selectedPage = 0;