I want to send widget.token to the User constructor but I cannot and it shows this error:
The instance member 'widget' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
This is my code:
class HomeScreen extends StatefulWidget {
final String token;
const HomeScreen(this.token, {Key? key}) : super(key: key);
@override
createState() {
return HomeScreenState();
}
}
@override
class HomeScreenState extends State<HomeScreen> {
int _selectedIndex = 2;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static final List<Widget> _widgetOptions = <Widget>[
User(widget.token),
const Profile(),
News(),
SingleChildScrollView(
child: Search(),
),
ChartAl('null', 'Line'),
// Home(),
];
@override
Widget build(BuildContext context) {
.....
...
...
..
CodePudding user response:
Simply, you cannot use widget
to initialize attributes of your state.
You should access it in the initState
, or in the build
function. Another possibility:
List<Widget> get _widgetOptions => <Widget>[
User(widget.token),
const Profile(),
News(),
SingleChildScrollView(
child: Search(),
),
ChartAl('null', 'Line'),
// Home(),
];
Also, you can never access an instance variable in a static context.