我正在FutureBuilder
屏幕上使用BottomNavigationBar
。但是,每当我单击其他选项卡并返回时,FutureBuilder
都会重新加载所有内容。我已经在使用AutomaticKeepAliveClientMixin
,在保存 getLessons()时遇到了麻烦,所以我不必再次加载它。有人可以帮我吗?
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Lesson>>(
future: getLessons(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none) {
} else if (snapshot.connectionState == ConnectionState.waiting) {
} else {
return Container();
}
});
}
这是我的getLessons():
Future<List<Lesson>> getLessons() async {
String url = "...";
http.Response response = await http.get(url);
var data = json.decode(response.body);
(...)
return lessons;
}
如何维护状态以免更新?
答案 0 :(得分:1)
// Create instance variable
Future myFuture;
@override
void initState() {
super.initState();
// assign this variable your Future
myFuture = getLessons();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Lesson>>(
future: future, // use your future here
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none) {
} else if (snapshot.connectionState == ConnectionState.waiting) {
} else {
return Container();
}
});
}
答案 1 :(得分:0)
问题是我没有使用PageView
来调用屏幕。我在build()
外部启动了4个屏幕,并在PageView
内将它们全部调用,现在可以使用了。
body: PageView(
controller: _pageController,
onPageChanged: (index) {
setState(() {
_index = index;
});
},
children: [_container1, _container2, _container3, _container4],
),