![](/img/trans.png)
[英]Is using widget.[variable_name] the best way to reference StatefulWidget variables?
[英]Is that possible to use the passing data form another page in Statefulwidget without using "widget."
嗨,我是這個工具的新手,我需要你的幫助。 讓我來解釋一下要做什么,我有一個Nav()
Statefulwidget,它傳遞bool
形成另一個頁面來檢查現在使用該應用程序的人是“用戶”還是“訪客”,在Nav()
中我使用BottomNavigationBarItem小部件。 現在的問題是BottomNavigationBarItem需要在BuildContext
之外創建列表,並且列表中包含需要導航的頁面。 我有一個名為Profile()
的頁面也需要傳遞bool
來檢查用戶狀態,我想使用已經傳遞的bool user
將數據傳遞給Profile()
頁面,但看起來我可以' 在BuildContext
外部調用user
。 我什至使用widget.user
但它仍然有一個錯誤說
“無法在初始化程序中訪問實例成員‘widget’。嘗試用不同的表達式替換對實例成員的引用”
無論如何,我可以在BuildContext
之外調用user
嗎?
因此,如果有人可以幫助我,我將非常感激。
這是代碼:
class Nav extends StatefulWidget {
const Nav({Key? key, required this.user}) : super(key: key);
final bool user;
@override
_NavState createState() => _NavState();
}
class _NavState extends State<Nav> {
int _selectedIndex = 0;
final bool _user = widget.user;
final List<Widget> _widgetOptions = <Widget>[
Home(),
News(),
Timeline(),
Manual(),
Profile(user: _user),
];
void _onItemTap(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: IndexedStack(
index: _selectedIndex,
children: _widgetOptions,
),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: const Color(0xFF20348F),
selectedItemColor: Colors.amber,
unselectedItemColor: Colors.white54,
items: [
bottomNav(const Icon(Icons.home), 'Home'),
bottomNav(const Icon(Icons.line_style_outlined), 'News'),
bottomNav(const Icon(Icons.location_pin), 'Timeline'),
bottomNav(const Icon(Icons.my_library_books_outlined), 'Manual'),
bottomNav(const Icon(Icons.person), 'Profile'),
],
currentIndex: _selectedIndex,
onTap: _onItemTap,
selectedFontSize: 15.0,
),
);
}
}
BottomNavigationBarItem bottomNav(Icon Icon, String Txt) {
return BottomNavigationBarItem(icon: Icon, label: Txt);
}
如果您使用的是空安全版本,則可以像這樣初始化它們。
class _NavState extends State<Nav> {
int _selectedIndex = 0;
late bool _user;
late List<Widget> _widgetOptions;
@override
void initState() {
_user = widget.user;
_widgetOptions = <Widget>[
Home(),
News(),
Timeline(),
Manual(),
Profile(user: _user),
];
super.initState();
}
此外,我強烈建議您使用 enum 而不是 bool 來指定用戶類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.