Search code examples
flutterdartflutter-layout

Is it possible to switch between pages PageView with ToggleButtons in Flutter?


I tried to give ToggleButtons pageController, but it doesn't work.


Solution

  • You can scroll pageView on Switch toggle like this:

    Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: ToggleButtons(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    '1',
                    style: TextStyle(fontSize: 16),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text(
                    '2',
                    style: TextStyle(fontSize: 16),
                  ),
                ),
              ],
              onPressed: (int index) {
                setState(() {
                  if (index == 1) {
                    controller.nextPage(
                        duration: Duration(milliseconds: 300),
                        curve: Curves.easeInOut);
                  } else {
                    controller.previousPage(
                        duration: Duration(milliseconds: 300),
                        curve: Curves.easeInOut);
                  }
                  for (int i = 0; i < isSelected.length; i++) {
                    isSelected[i] = i == index;
                  }
                });
              },
              isSelected: isSelected,
            ),
          ),
          Expanded(
            child: PageView(
              controller: controller,
              children: [
                Container(
                  color: Colors.red,
                ),
                Container(
                  color: Colors.yellow,
                ),
              ],
            ),
          ),
        ],
      )
    

    enter image description here