简体   繁体   中英

Using optional parameter in widget

I am getting a variable to a widget optionally and i want to use it.

class MainPage extends StatefulWidget {
  final String? uyeId;
  MainPage({
    Key? key,
    this.uyeId,
  }) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {

  int pageIndex = 0;
  List<Widget> pageList = <Widget>[
    Anasayfa(uyeId: widget.uyeId),
    Mesajlar(),
    Mesajlar(),
    Bildirimler(
      uyeId: "1999",
    ),
    Hesabim()
  ];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

Error is The instance member 'widget' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression. How i can use that parameter?

You can pass the value to the variable in initState like this:

late List<Widget> pageList;

initState:

@override
void initState() {
pageList = <Widget>[
Anasayfa(uyeId: widget.uyeId),
Mesajlar(),
Mesajlar(),
Bildirimler(
  uyeId: "1999",
),
Hesabim()];
super.initState();
  }

You can try this:

First create a variable of type list :

List<Widget> pageList = []

Second create method initState :

void initState(){
  super.initState();
}

Then you can create a function filling the list with data:

void fillingList(){
    pageList = [
        Anasayfa(uyeId: widget.uyeId),
        Mesajlar(),
        Mesajlar(),
        Bildirimler(
           uyeId: "1999",
         ),
        Hesabim()
     ];
  }

And finally you can call the function in the method initState:

void initState(){
  super.initState();
   fillingList();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM