I'm making an app that consists of two sections. One is a PageView section you can change pages with a Swipe motion. Another shows which page you are in now after you change pages. But there is time delay. When I change pages like page one to page two, the lower section's change with about 0.5-second delay.
To find any causes, I declared index as double(It's redeclared as int now). And I found when I change pages in my first section PageView, the lower section shows decimal change(i.g. not 1 -> 2, but 1.0 -> 1.xxx -> 2). I also tried the Switch-case statement. In this statement, default is returns Text('nothing'). And I found when being changed, the lower section shows nothing.
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
static final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
final controller = PageController(initialPage: 0);
var scrollDirection = Axis.horizontal;
var actionIcon = Icons.swap_vert;
int index;
@override
void initState() {
super.initState();
index = 0;
controller.addListener(() {
setState(() {
index = controller.page.toInt();
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
centerTitle: true,
title: Text('it\'s a drill for page view'),
),
body: _buildBody(),
);
}
Widget _buildBody() {
return SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: PageView.builder(
controller: controller,
itemCount: 5,
itemBuilder: (context, index) {
return Text('it is $index');
},
)
),
Expanded(
child: FittedBox(
fit: BoxFit.fitWidth,
child: Container(
color: Colors.blue,
child: _showContent()
),
),
)
],
),
);
}
Widget _showContent() {
switch (index) {
case 0: return Text('One');
break;
case 1: return Text('Two');
break;
case 2: return Text('Three');
break;
case 3: return Text('Four');
break;
case 4: return Text('Five');
break;
default: return Text('Nothing');
}
}
}
I want two-section not to have any delays. Is there any solution? Please help me. I'm a real beginner. So maybe I beg your pardon. But I never let this question left unattended. Thank you very much.
Probably rounding the value of the current page in the PageController listener is more suitable for you.
Here is the modified listener code:
controller.addListener(() {
setState(() {
index = controller.page.round();
});
});