Search code examples
flutterdartflutter-pageview

Can I use for loop to create class?


I create swipe app for swipe Page1(), Page2() in main.dart which class Page1(), Page2() show in pages.dart. All code I use from this tutorial (github).

I want to create 30 pages. Can I use for loop to create 30 class ?

main.dart

class _MyHomePageState extends State<MyHomePage> {
  int _seletedItem = 0;
  var _pages = [Page1(), Page2()];
  var _pageController = PageController();

pages.dart

class Page1 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Center(child: Text('First Page', style: TextStyle(fontSize: 50.0),),),);
  }
}

class Page2 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Center(child: Text('Second Page',style: TextStyle(fontSize: 50.0),),),);
  }
}

Solution

  • You can do it like this example here i am passing index as param to page but you can pass your custom data from your custom list too.

    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key}) : super(key: key);
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _seletedItem = 0;
      var _pageController = PageController();
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Page Controller looop - Demo'),
          ),
          body: PageView(
            children: List<Widget>.generate(1000,(i) => Page(i:i);,
            onPageChanged: (index) {
              setState(() {
                _seletedItem = index;
              });
            },
            controller: _pageController,
          ),
         
        );
      }
    }
    
    
    class Page extends StatelessWidget {
      final i;
    
      const Page({Key key, this.i}) : super(key: key);
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Text(
              '$i Page',
              style: TextStyle(fontSize: 50.0),
            ),
          ),
        );
      }
    }