Вы можете скопировать пасту и запустить полный код ниже
Вы можете использовать PageView.builder
фрагмент кода
List<Widget> listWidget = [Red(), Yellow(), Blue()];
...
return PageView.builder(
controller: pageController,
onPageChanged: (index) {
pageChanged(index);
},
itemCount: listWidget.length,
itemBuilder: (BuildContext context, int index) {
return listWidget[index];
},
);
рабочая демонстрация
полный код
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Widget> listWidget = [Red(), Yellow(), Blue()];
int bottomSelectedIndex = 0;
List<BottomNavigationBarItem> buildBottomNavBarItems() {
return [
BottomNavigationBarItem(
icon: new Icon(Icons.home), title: new Text('Red')),
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: new Text('Blue'),
),
BottomNavigationBarItem(
icon: Icon(Icons.info_outline), title: Text('Yellow'))
];
}
PageController pageController = PageController(
initialPage: 0,
keepPage: true,
);
Widget buildPageView() {
return PageView.builder(
controller: pageController,
onPageChanged: (index) {
pageChanged(index);
},
itemCount: listWidget.length,
itemBuilder: (BuildContext context, int index) {
return listWidget[index];
},
);
}
@override
void initState() {
super.initState();
}
void pageChanged(int index) {
setState(() {
bottomSelectedIndex = index;
});
}
void bottomTapped(int index) {
setState(() {
bottomSelectedIndex = index;
pageController.animateToPage(index,
duration: Duration(milliseconds: 500), curve: Curves.ease);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: buildPageView(),
bottomNavigationBar: BottomNavigationBar(
currentIndex: bottomSelectedIndex,
onTap: (index) {
bottomTapped(index);
},
items: buildBottomNavBarItems(),
),
);
}
}
class Red extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text("Red");
}
}
class Blue extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text("Blue");
}
}
class Yellow extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text("Yellow");
}
}