Home > Enterprise >  Flutter/Dart pass an argument in an array?
Flutter/Dart pass an argument in an array?

Time:11-16

So I am trying to change a page in Flutter, here's my code:

class _RootAppState extends State<RootApp> {
  int tabIndex = 0;

  final pages = [
    Start(),
    Quiz(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueAccent,
      body: getBody(),
    );
  }

  Widget getBody() {
    return pages[tabIndex];
  }
}

and I thought I will create a constructor for Start() and Quiz() class to pass tabIndex argument because the other pages need this integer to be used for another change.

But passing an argument in an array gets me an error

The instance member 'tabIndex can’t be accessed in an initializer.

I can pass an argument in body: Start(tabIndex) But what if I wanted to do it in an array of my pages? Is this possible or should I look for another solution?

Thank you

CodePudding user response:

use pages[tabIndex] in body directly it will work

CodePudding user response:

You must ensure that Start() and Quiz() are Widget But maybe you should take a closer look at PageView.

CodePudding user response:

If you refactor the initialization of tabIndex and pages to be handled by the constructor, then you should be able to initialize pages as described:

class RootApp extends StatefulWidget {
  const RootApp({Key? key}) : super(key: key);

  @override
  _RootAppState createState() => _RootAppState();
}

class _RootAppState extends State<RootApp> {
  _RootAppState({this.tabIndex = 0})
      : pages = [
          Start(tabIndex: tabIndex),
          Quiz(tabIndex: tabIndex),
        ];

  int tabIndex;

  final List<Widget> pages;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueAccent,
      body: getBody(),
    );
  }

  Widget getBody() {
    return pages[tabIndex];
  }
}

class Start extends StatelessWidget {
  const Start({Key? key, required this.tabIndex}) : super(key: key);
  final int tabIndex;
  @override
  Widget build(BuildContext context) => Text('Start Placeholder $tabIndex');
}

class Quiz extends StatelessWidget {
  const Quiz({Key? key, required this.tabIndex}) : super(key: key);
  final int tabIndex;
  @override
  Widget build(BuildContext context) => Text('Quiz Placeholder $tabIndex');
}
  • Related