简体   繁体   中英

Flutter/Dart pass an argument in an array?

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

直接在正文中使用pages[tabIndex]它将起作用

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');
}

您必须确保Start()Quiz()Widget但也许您应该仔细看看PageView

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