【发布时间】:2021-07-25 01:30:52
【问题描述】:
我正在尝试将从另一个类接收到的参数用户名传递给我的 HomePage 类。 我想将该参数从 HomePageState 传递给另一个名为 Profile 的类。
我尝试使用“widget.username”方法从 _HomePageState 访问用户名参数。但它给出了一个错误提示“无法在初始化程序中访问实例成员'widget'”。
下面是 HomePage 类的代码供大家参考:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:codeforces_data_flutter/screens/profile.dart';
class HomePage extends StatefulWidget {
String username;
HomePage({this.username});
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
static const widgetStyle =
TextStyle(fontWeight: FontWeight.bold, fontSize: 30.0);
int selectedIndex = 0;
List<Widget> widgetsToDisplay = [
Profile(
username: widget.username, /*Error is on this line*/
),
Center(
child: Text(
'Index 1 : Previous Contests',
style: widgetStyle,
),
),
Center(
child: Text(
'Index 2 : Upcoming Contests',
style: widgetStyle,
),
),
Center(
child: Text(
'Index 3 : About Me',
style: widgetStyle,
),
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(
CupertinoIcons.profile_circled,
),
label: 'User Profile',
backgroundColor: Colors.teal,
),
BottomNavigationBarItem(
icon: Icon(
CupertinoIcons.arrow_counterclockwise,
),
label: 'Previous Contests',
backgroundColor: Colors.blue,
),
BottomNavigationBarItem(
icon: Icon(
CupertinoIcons.arrow_clockwise,
),
label: 'Upcoming Contests',
backgroundColor: Colors.green,
),
BottomNavigationBarItem(
icon: Icon(
CupertinoIcons.suit_heart,
),
label: 'About Me',
backgroundColor: Colors.pink,
),
],
currentIndex: selectedIndex,
selectedItemColor: Colors.yellow,
onTap: (index) {
setState(() {
selectedIndex = index;
});
},
),
body: widgetsToDisplay[selectedIndex],
);
}
}
问题出在 widgetsToDisplay 列表中,当通过传递 widget.username 为 username 属性调用 Profile 类时。
我已经使用注释标记了给出错误的行。
感谢任何帮助。谢谢。
【问题讨论】:
标签: flutter dart parameter-passing flutter-widget flutter-state