How to add different items to a Page View Flutter

Issue

I have this code which allows me to scroll between cards that hold text. However, all it does is add the same text on each card. I want to display two separate pieces of text which are kept inside

HomeInfo()
Achieve()

This is the code I currently have:


SizedBox(
                    height: 300,
                      child: PageView.builder(
                        itemCount: 2,
                        controller: PageController(viewportFraction: 0.7),
                        onPageChanged: (int index) =>
                            setState(() => _index = index),
                        itemBuilder: (_, i) {
                          return Transform.scale(
                            scale: i == _index ? 1 : 0.9,
                            child: Card(
                              elevation: 6,
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(20)),
                              child: Center(
                                child: HomeInfo(),
                              ),
                            ),
                          );
                        },
                      ),
                    ), 

I am really confused on how to do this. (I just started getting into coding)
Thanks

Solution

You need to check for the index and return the appropriate widget.

You can achieve this way:

SizedBox(
                    height: 300,
                      child: PageView.builder(
                        itemCount: 2,
                        controller: PageController(viewportFraction: 0.7),
                        onPageChanged: (int index) =>
                            setState(() => _index = index),
                        itemBuilder: (_, i) {

                          return Transform.scale(
                            scale: i == _index ? 1 : 0.9,
                            child: Card(
                              elevation: 6,
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(20)),
                              child: Center(
                                child: i == 0 ? HomeInfo() : Achieve(), // this line
                              ),
                            ),
                          );
                        },
                      ),
                    ),  

Answered By – OMi Shah

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *