I am trying to pass data to another screen but I am faced with 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
A number of users have posted a similar question, and I have actually gone through most of them but none of those given solutions seems to work in my case
I tried without the widget but it still didn't work. I mean I tried this department.name
class MainScreen extends StatefulWidget {
const MainScreen({Key? key, required this.department}) : super(key: key);
final Department department;
@override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
int _selectedIndex = 0;
static List<Widget> _widgetOptions = <Widget>[
HomeView(
department: Department(
name: widget.department.name,// The error is here.
stream: '',
description: '',
author: '',
availability: true,
hod: '',
totalNoBooks: 0),
),
RequestedBooks(),
ProfileScreen(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Center(
child: Text("Some Text Here"),
),
),
);
}
}
I don't have a problem with the receiving screen. This is an excerpt of the code in the receiving screen
class HomeView extends StatefulWidget {
const HomeView({
Key? key,
required this.department,
}) : super(key: key);
final Department department;
@override
_HomeViewState createState() => _HomeViewState();
}
CodePudding user response:
Try adding widgets in the initstate
late List<Widget> _widgetOptions = [];
@override
void initState(){
_widgetOptions = <Widget>[
HomeView(
department: Department(
name: widget.department.name,// The error is here.
stream: '',
description: '',
author: '',
availability: true,
hod: '',
totalNoBooks: 0),
),
RequestedBooks(),
ProfileScreen(),
];
}
CodePudding user response:
You can just include late like
late List<Widget> _widgetOptions = <Widget>[ ..]
Note that it can't be done with class variables(static variables)
This is known as Lazy initialization. Also it cant be be static
Also, you can use initState which is more common way of assigning data.
late List<Widget> _widgetOptions ; //this can be static
@override
void initState() {
super.initState();
_widgetOptions = <Widget>[
//...
];
}