如何在不"FlutterError setState() or markNeedsBuild() called during build."的情况下使用底部导航栏更改页面



所以我设置了一个底部导航栏,在5个不同的页面之间切换,这些页面分为5个不同文件,第6个作为实际的导航栏页面。问题是,我甚至无法使用路由或命名路由更改页面。

这是我在主页中的代码。

import 'package:flutter/material.dart';
import 'package:fluttericon/typicons_icons.dart';
import 'package:luxview/Custom/Themes.dart';
import 'package:luxview/Pages/Messages.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _currentIndex = 0;
Widget _currentWidget = Container();
@override
void initState() {
super.initState();
_Screen();
}
void _Screen() {
// Area where I tried to set up screen switching
switch (_currentIndex) {
case 0:
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => const MessagePage()));
//case 1:
//  Themes
//case 2:
//  Plugins
//case 3:
//  Profile
//case 4:
//  Settings
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _currentWidget,
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() => _currentIndex = index);
_Screen();
},
backgroundColor: bottomnavbar_bgc,
selectedItemColor: bottomnavbar_selcol,
unselectedItemColor: Colors.blue,
type: BottomNavigationBarType.fixed,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.message),
label: "Messages",
),
BottomNavigationBarItem(icon: Icon(Icons.brush), label: "Themes"),
BottomNavigationBarItem(
icon: Icon(Typicons.puzzle), label: "Plugins"),
BottomNavigationBarItem(
icon: Icon(Icons.account_box), label: "Profile"),
BottomNavigationBarItem(
icon: Icon(Icons.settings), label: "Settings"),
]),
);
}
}

这是我在messages.dart文件中的内容,以备不时之需。

import 'package:flutter/material.dart';
import 'package:luxview/Custom/Themes.dart';
class MessagePage extends StatefulWidget {
const MessagePage({super.key});
@override
_MessagePageState createState() => _MessagePageState();
}
class _MessagePageState extends State<MessagePage> {
@override
Widget build(BuildContext context) {
return Container(
color: universal_bgc,
);
}
}

如果您只想更新页面。

class MainPage extends StatefulWidget {
const MainPage({super.key});
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int _currentIndex = 0; //keep track of current selected index.
@override
Widget build(BuildContext context) {
Widget selectedWidget = Home();
switch (_currentIndex) {
case 0:
selectedWidget = Home();
break;
case 1:
selectedWidget = Page2();
break;
...
}
return Scaffold(
body: selectedWidget,
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() => _currentIndex = index);
},
...
),
);
}
}

最新更新