【发布时间】:2022-07-23 00:09:27
【问题描述】:
我正在使用 FutureBuilder 并在 InitState 中初始化 _future,如 here 所述。
尽管如此,每次我使用BottomNavigationBar 切换页面时,FutureBuilder 都会重新构建自己。
代码示例:
class _HomeViewState extends State<HomeView> {
late final Future<List<DocumentSnapshot<Object?>>> _futureSerieA;
@override
void initState() {
super.initState();
_futureSerieA = getScheduled("Serie A");
}
@override
Widget build(BuildContext context) {
return SizedBox.expand(
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(0,0,0,0),
child: Container(
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: Colors.transparent)
)
),
child: Theme(
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
child: FutureBuilder(
future: _futureSerieA,
builder: (context, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
if (snapshot.hasData) {
List<String> scheduled = [];
for (var DOC in snapshot.data!) {
scheduled.add(DOC.id);
}
return ...
在BottomNavigationBar的页面之间浏览时如何禁用FutureBuilder重新构建?
底部导航栏:
class _LoggedHandleState extends State<LoggedHandle> {
);
double height = AppBar().preferredSize.height;
int _selectedPage = 1;
final _pageOptions = [
const BetView(),
const HomeView(),
const UserView()
];
@override
Widget build(BuildContext context) {
return Scaffold(
...
),
bottomNavigationBar: BottomNavigationBar(
unselectedItemColor: Colors.white60,
backgroundColor: Colors.red,
selectedItemColor: Colors.white,
currentIndex: _selectedPage,
onTap: (int index) {
setState(() {
_selectedPage = index;
});
},
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.receipt),
label: 'Schedina',
),
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
label: 'Account',
),
]),
body: _pageOptions[_selectedPage],
);
}
}
【问题讨论】:
-
我更喜欢在
StatefulWidget上使用可空数据 -
这会影响
FutureBuilder的行为吗? -
你能提供一个简化的小部件来重现同样的错误
-
很复杂,未来
getScheduled与FirebaseAuth和Firestore一起工作...我可以附上BottomNavigationBar的代码,我认为问题是每次更改时都会调用InitState页面 -
你可以创建一个虚拟的未来来重现错误
标签: flutter dart flutter-futurebuilder