I am trying to pass the parameter username which has been received from another class to my HomePage class. I want to pass that parameter from the HomePageState to another class called Profile.
I tried using the "widget.username" method to get access to the username parameter from the _HomePageState. But it gives an error saying "The instance member 'widget' can't be accessed in an initializer".
Below is the code of the HomePage class for your reference:
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],
);
}
}
The problem lies in the widgetsToDisplay list when the Profile class is called with passing widget.username for the username property.
I have marked the line which gives the error using a comment.
Any help is appreciated. Thank You.