gpt4 book ai didi

flutter - 如何在 flutter 中重新创建单个小部件并使其失去状态?

转载 作者:行者123 更新时间:2023-12-05 04:55:14 24 4
gpt4 key购买 nike

我有一个小部件,我想重新创建状态,我该怎么做才能实现这个目标?我听说 UniqueKey 有一种方法,但我不太了解它们,因为我是初学者(别担心,我已经搜索过了)

到目前为止,我尝试的是pop Navigator,然后再次push 相同的页面...它有效...但问题是当我的页面脱离状态时,我正在丢失 BottomNavigationBar...

到目前为止,这是我解决这个问题的方法


@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive ||
state == AppLifecycleState.paused) {
Navigator.pop(context);
Navigator.push(
context, MaterialPageRoute(builder: (context) => Home()));
}
super.didChangeAppLifecycleState(state);
}


底部导航栏


int _selectedItem = 0;
PageController pageController;

void _onPageChanged(int pageIndex) {
setState(() {
_selectedItem = pageIndex;
});
}

void _onTapped(int pageIndex) {
setState(() {
_selectedItem = pageIndex;
});
pageController.jumpToPage(pageIndex);
}

@override
void initState() {
pageController = PageController();
super.initState();
}

@override
void dispose() {
pageController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: pageController,
children: pages,
onPageChanged: _onPageChanged,
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: bottomNavigationBarItems(context), // You can find this below
currentIndex: _selectedItem,
onTap: _onTapped,
),
);
}
}


bottomNavigationBarItems


List<BottomNavigationBarItem> bottomNavigationBarItems(BuildContext context) {
final AppLocalization translate = AppLocalization.of(context);
final BottomNavigationBarItem homePage = BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.home),
label: translate.translate('home'),
);

final BottomNavigationBarItem newsPage = BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.newspaper),
label: translate.translate('news'),
);

final BottomNavigationBarItem programsPage = BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.tv),
label: translate.translate('programs'),
);
return [
homePage,
newsPage,
programsPage,
];
}

最佳答案

任何小部件都可以

key: UniqueKey(),

调用setState时会丢失当前状态并再次重建

关于flutter - 如何在 flutter 中重新创建单个小部件并使其失去状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65491982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com