【发布时间】:2019-01-02 04:56:35
【问题描述】:
我目前正在开发一个具有多个页面并使用底部导航栏的应用程序,每个页面都需要向不同的 API 端点发送 HTTP GET 请求。
现在我在每个页面的 initState() 中调用 get 函数。结果,每次我点击导航栏转到相应的页面时,它都会重新发送另一个HTTP GET请求。我该如何处理?我应该从底部导航页面发送 GET 请求吗?
我尝试过使用 PageStorageKey 方法,但我认为问题在于我在每个页面的 initState 中调用了 GET 方法。
MyTab.dart
bottomNavigationBar: Theme(
data: Theme.of(context).copyWith(
// sets the background color of the `BottomNavigationBar`
canvasColor: Color(0xff3a3637),
// sets the active color of the `BottomNavigationBar` if `Brightness` is light
primaryColor: Color(0xffffd51e),
textTheme: Theme.of(context).textTheme.copyWith(
caption: TextStyle(color: Colors.white),
),
), // sets the inactive color of the `BottomNavigationBar`
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: currentTab,
onTap: (int index) {
setState(() {
currentTab = index;
currentPage = pages[index];
});
},
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/anggota_white.png")),
title: Text(
'Anggota',
style: TextStyle(fontFamily: 'MyriadPro'),
),
),
BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/bk_white.png")),
title: Text(
"BK",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),
BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/himatif_white.png")),
title: Text(
"Himatif",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
title: Text(
"Cari",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),
BottomNavigationBarItem(
icon: ImageIcon(AssetImage("assets/icon/kkm_white.png")),
title: Text(
"KKM",
style: TextStyle(fontFamily: 'MyriadPro'),
),
),
],
),
),
这是一页,
AnggotaScreen.dart
class AnggotaScreen extends StatefulWidget {
AnggotaScreen({
Key key,
}) : super(key: key);
@override
_AnggotaScreenState createState() => _AnggotaScreenState();
}
class _AnggotaScreenState extends State<AnggotaScreen> {
bool _isLoading;
var _dataAngkatan, _dataTahun;
static String _uriAngkatan;
_ambilData(String url, bool tipe) async {
final response = await http.get(url);
if (response.statusCode == 200) {
final map = json.decode(response.body);
if (tipe == true) {
setState(() {
_dataAngkatan = map;
_isLoading = false;
});
} else {
setState(() {
_dataTahun = map;
_isLoading = false;
});
}
}
}
// initState
@override
void initState() {
super.initState();
_isLoading = true;
_uriAngkatan = "2012";
_dataAngkatan = [];
_dataTahun = [];
_ambilData(Url.TAHUN_ANGGOTA, false);
_ambilData(Url.angkatan(_uriAngkatan), true);
}
..........
}
我想让页面在开始时只发送一次 GET 请求并保持该状态直到应用程序关闭,但现在它会在我每次打开该页面时发送 GET 请求。
【问题讨论】: