flutter - 当页面在屏幕中显示时如何加载页面内容
问题描述
在这里,我有bottomNavigationBar在页面之间移动,因此当主页加载时,所有类都将加载并运行initState,但在initState我有获取数据的 http 请求;所以当我第一次显示主页时所有的http请求都会运行......我只需要在用户滑动到那个页面时运行那个页面的http请求
class Home extends StatefulWidget {
const Home({Key key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: IndexedStack(
index: _currentIndex,
children: [
Partner(),
Partners(),
],
),
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
setState(() {
_currentIndex = index;
});
},
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
title: Text('Partner'),
),
BottomNavigationBarItem(
title: Text('Partners'),
),
],
),
);
}
}
解决方案
您可以改用TabBarView
如下方式:
class _HomeState extends State<Home> with SingleTickerProviderStateMixin { // necessary
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: TabBarView(
controller: _tabController,
children: <Widget>[Partner(),Partners()],
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
_tabController.animateTo(index);
},
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
title: Text('Partner'),
),
BottomNavigationBarItem(
title: Text('Partners'),
),
],
),
);
}
@override
void dispose() {
super.dispose();
_tabController.dispose();
}
推荐阅读
- java - 无法解释伪代码行(RSA 乘法逆)
- java - (Java)当自定义对象在数组中时,如何操作自定义对象的变量?
- r - 如果值与向量中的任何字符串匹配,则字符串匹配
- regex - REGEX .net\powershell 匹配字符串之间的字符串
- gitlab - 如何在 Mattermost 中为 JIRA 或 Gitlab 中的所有状态更改生成通知?
- git - gitflow 为什么我们需要master
- powershell - Powershell 上的 CURL 脚本,用于从 HTTPS URL 获取响应,并且还想提供用户名/密码
- java - 为什么 DCL 使用 volatile 而不使用 final?我的代码运行相同的效果
- javascript - 在 React 中为单个子组件设置样式
- c++ - C ++递归查找数组的最小值