Flutter底部导航栏静态成员初始化错误求助:传递UID至子页面
Let's break down and fix this error you're facing. The core problem here is how you're initializing your pages list in the state class.
Why the Error Happens
When you declare var pages = [...] directly as a member variable in your _ProfilePage class, this initialization runs before the class instance is fully created. At this stage, non-static instance variables like uid aren't available yet—only static members can be accessed during this early initialization phase.
Solution 1: Initialize pages in initState()
This is the most common and reliable approach. We'll declare pages with the late keyword to delay initialization, then populate it inside initState() once the instance is ready:
class _ProfilePage extends State<MyStatefulWidget> { final String uid; _ProfilePage(this.uid); @override void initState() { super.initState(); // Initialize pages here after the instance is created pages = [ LearningRoom(), BrandRanking(), Profile(uid), // Now uid is accessible FabricCalculator(), LookBook() ]; } int i = 2; late List<Widget> pages; // Use 'late' to delay initialization }
Solution 2: Use a Getter Method
If your pages list doesn't need to be cached (or if you want it to reflect any updates to uid automatically), you can use a getter instead of a static initializer:
class _ProfilePage extends State<MyStatefulWidget> { final String uid; _ProfilePage(this.uid); @override void initState() { super.initState(); } int i = 2; // Getter generates the list on each access List<Widget> get pages => [ LearningRoom(), BrandRanking(), Profile(uid), FabricCalculator(), LookBook() ]; }
Bonus: Follow Flutter Best Practices
You can simplify your code further by leveraging the widget property in the state class. Instead of passing uid to the state constructor, you can directly access widget.uid (since widget references the parent MyStatefulWidget instance):
class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key? key, required this.uid}) : super(key: key); final String uid; @override _ProfilePage createState() => _ProfilePage(); // No need to pass uid here } class _ProfilePage extends State<MyStatefulWidget> { @override void initState() { super.initState(); pages = [ LearningRoom(), BrandRanking(), Profile(widget.uid), // Use widget.uid directly FabricCalculator(), LookBook() ]; } int i = 2; late List<Widget> pages; }
This approach keeps your code aligned with Flutter's state management patterns, as the state class is designed to access properties from its parent widget via the widget property.
内容的提问来源于stack exchange,提问作者Someone

