当我尝试在Flutter中实现底部导航栏时,为什么我的应用会崩溃?

7z5jn7bk  于 2022-12-30  发布在  Flutter
关注(0)|答案(2)|浏览(153)

我正在尝试实现一个可以访问不同页面的bottomNavigationBar,到目前为止,我已经完成了大部分的工作,你可以在下面的代码中看到。
下面是我在navBar.dart中的bottomNavigationBar代码:

// ignore: file_names
import 'package:bottom_navy_bar/bottom_navy_bar.dart';
import 'package:flutter/material.dart';

import '../views/home_page.dart';
import '../views/secondScreen.dart';

// ignore: camel_case_types
class navBar extends StatefulWidget {
  const navBar({Key? key}) : super(key: key);

  @override
  State<navBar> createState() => _navBarState();
}

// ignore: camel_case_types
class _navBarState extends State<navBar> {
  int currentIndex = 0;
  final screens = [
    const HomePage(),
    const SecondRoute(),
    const SecondRoute(),
    const SecondRoute(),
  ];

  @override
  Widget build(BuildContext context) {
    screens[currentIndex];
    return BottomNavyBar(
      animationDuration: const Duration(milliseconds: 260),
      curve: Curves.ease,
      showElevation: false,
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      selectedIndex: currentIndex,
      onItemSelected: (index) {
        setState(() {
          currentIndex = index;
        });
        // Push the new page onto the navigation stack
        // Navigator.push(
        //   context,
        //   MaterialPageRoute(builder: (context) => pages[index]),
        // );
      },
      items: <BottomNavyBarItem>[
        BottomNavyBarItem(
          inactiveColor: const Color.fromARGB(255, 20, 143, 199),
          activeColor: const Color.fromARGB(255, 5, 176, 255),
          textAlign: TextAlign.center,
          icon: const Icon(Icons.home),
          title: const Text('Home'),
        ),
        BottomNavyBarItem(
          inactiveColor: const Color.fromARGB(255, 20, 143, 199),
          activeColor: const Color.fromARGB(255, 5, 176, 255),
          textAlign: TextAlign.center,
          icon: const Icon(Icons.discord),
          title: const Text('Discord'),
        ),
        BottomNavyBarItem(
          inactiveColor: const Color.fromARGB(255, 20, 143, 199),
          activeColor: const Color.fromARGB(255, 5, 176, 255),
          textAlign: TextAlign.center,
          icon: const Icon(Icons.school),
          title: const Text('Examotron'),
        ),
        BottomNavyBarItem(
          inactiveColor: const Color.fromARGB(255, 20, 143, 199),
          activeColor: const Color.fromARGB(255, 5, 176, 255),
          textAlign: TextAlign.center,
          icon: const Icon(Icons.document_scanner),
          title: const Text('Notes'),
        ),
      ],
    );
  }
}

这里是我的主页home_page.dart

import 'package:xconcordia/services/remote_service.dart';
import 'package:flutter/material.dart';
import 'package:xconcordia/views/secondScreen.dart';
import 'package:xconcordia/widgets/categoryPicker.dart';
import '../widgets/libraryCards.dart';
import '../widgets/libraryStatsHeader.dart';
import '../widgets/navBar.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

var webb = '';
String webOccupancy = '';
String greyOccupancy = '';
String vannierOccupancy = '';
String libTime = '';
String webLevel = '';
String greyLevel = '';
String vannierLevel = '';

class _HomePageState extends State<HomePage> {
  bool isLoading = false;
  int currentIndex = 1;

  // List of pages
  List<Widget> pages = [
    const HomePage(),
    const SecondRoute(),
    const SecondRoute(),
    const SecondRoute(),
  ];
  @override
  void initState() {
    super.initState();
    _fetchWebOccupancy();
    _fetchVannierOccupancy();
    _fetchGreyOccupancy();
    _fetchLibTime();
  }

  Future<void> _fetchLibTime() async {
    if (libTime == '') {
      String? libraryTime = await getDataAPI_time().getPosts();
      setState(() {
        libTime = libraryTime.toString();
      });
    }
  }

  Future<void> _fetchWebOccupancy() async {
    if (webOccupancy == '') {
      String? occupancy = await getDataAPI().getPosts();
      setState(() {
        webOccupancy = occupancy!.substring(0, occupancy.length - 5);
        if (webOccupancy == '' || int.parse(webOccupancy) < 0) {
          webOccupancy = '0';
        }
        if (int.parse(webOccupancy) > 100) {
          webLevel = 'High';
        } else if (int.parse(webOccupancy) > 75 &&
            int.parse(webOccupancy) < 100) {
          webLevel = 'Medium';
        } else {
          webLevel = 'Low';
        }
        isLoading = false;
      });
    }
  }

  Future<void> _fetchGreyOccupancy() async {
    if (greyOccupancy == '') {
      String? occupancy = await getDataAPI_G().getPosts();
      setState(() {
        greyOccupancy = occupancy!.substring(0, occupancy.length - 5);
        if (greyOccupancy == '' || int.parse(greyOccupancy) < 0) {
          greyOccupancy = '0';
        }
        if (int.parse(greyOccupancy) > 100) {
          greyLevel = 'High';
        } else if (int.parse(greyOccupancy) > 50 &&
            int.parse(greyOccupancy) < 100) {
          greyLevel = 'Medium';
        } else {
          greyLevel = 'Low';
        }
        isLoading = false;
      });
    }
  }

  Future<void> _fetchVannierOccupancy() async {
    if (vannierOccupancy == '') {
      String? occupancy = await getDataAPI_V().getPosts();
      setState(() {
        vannierOccupancy = occupancy!.substring(0, occupancy.length - 5);
        if (vannierOccupancy == '' || int.parse(vannierOccupancy) < 0) {
          vannierOccupancy = '0';
        }
        if (int.parse(vannierOccupancy) > 100) {
          vannierLevel = 'High';
        } else if (int.parse(vannierOccupancy) > 50 &&
            int.parse(vannierOccupancy) < 100) {
          vannierLevel = 'Medium';
        } else {
          vannierLevel = 'Low';
        }
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        // elevation: 15,
        // leading: IconButton(
        //   icon: const Icon(Icons.menu),
        //   onPressed: () {},
        // ),

        title: const Text('xConcordia'),
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Color.fromARGB(223, 57, 25, 163),
                offset: Offset(0, 0),
                blurRadius: 20,
              ),
            ],
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [Colors.blue, Colors.purple],
            ),
          ),
        ),
      ),
      body: isLoading
          ? const Center(
              child: LinearProgressIndicator(
              color: Color.fromARGB(162, 114, 68, 251),
            ))
          : Container(
              margin: const EdgeInsets.only(top: 20),
              child: Column(
                children: [
                  // ignore: prefer_const_constructors
                  LibraryStatsHeader(), //LibraryStatsHeader widget is in a file called libraryStatsHeader
                  const Padding(padding: EdgeInsets.all(10)),
                  libCards(), //libCards widget is in a file called libraryCards
                  const categoryPicker(), //category picker
                ],
              ),
            ),
      bottomNavigationBar: const navBar(),
    );
  }
}

上面代码中的问题是,尽管我的导航栏工作(如,点击它改变导航栏图标),页面状态没有改变(即,它不转到另一个页面,停留在当前页面)
现在,我意识到我没有对screens []数组做任何事情,所以我应该使用它,所以在我的navBar.dart中,我想返回body: screens[currentIndex]来使这个逻辑工作,所以我的导航栏是可用的。
因此,在这个navBar.dart文件中,我用Scaffold将返回值包围起来,并执行了以下操作:

Widget build(BuildContext context) {
      return Scaffold(
      body: screens[currentIndex],
      bottomNavigationBar: BottomNavyBar(
        animationDuration: const Duration(milliseconds: 250),
        curve: Curves.ease,
        showElevation: false,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        selectedIndex: currentIndex,
        onItemSelected: (index) {
          setState(() {
            currentIndex = index;
          });
          // Push the new page onto the navigation stack
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => pages[index]),
          // );
        },
        items: <BottomNavyBarItem>[
          BottomNavyBarItem(
            inactiveColor: const Color.fromARGB(255, 20, 143, 199),
            activeColor: const Color.fromARGB(255, 5, 176, 255),
            textAlign: TextAlign.center,
            icon: const Icon(Icons.home),
            title: const Text('Home'),
          ),
          BottomNavyBarItem(
            inactiveColor: const Color.fromARGB(255, 20, 143, 199),
            activeColor: const Color.fromARGB(255, 5, 176, 255),
            textAlign: TextAlign.center,
            icon: const Icon(Icons.discord),
            title: const Text('Discord'),
          ),
          BottomNavyBarItem(
            inactiveColor: const Color.fromARGB(255, 20, 143, 199),
            activeColor: const Color.fromARGB(255, 5, 176, 255),
            textAlign: TextAlign.center,
            icon: const Icon(Icons.school),
            title: const Text('Examotron'),
          ),
          BottomNavyBarItem(
            inactiveColor: const Color.fromARGB(255, 20, 143, 199),
            activeColor: const Color.fromARGB(255, 5, 176, 255),
            textAlign: TextAlign.center,
            icon: const Icon(Icons.document_scanner),
            title: const Text('Notes'),
          ),
        ],
      ),
    );
  }

这样做,我会得到一个相同错误的无限循环:

当我试图以screens[currentIndex]作为主体返回Scaffold时,我的逻辑中有什么缺陷?是错误的吗?否则我怎么让这个导航栏工作呢?

编辑:我已将导航栏添加到我的main.dart文件中,将home: HomePage()替换为navBar()

import 'package:flutter/material.dart';
import '../widgets/navBar.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: navBar(),
    );
  }
}

然而,我仍然得到同样的错误。

mccptt67

mccptt671#

在homePage()中,删除页面列表、currentIndex和底部导航栏。homePage()应如下所示:

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

var webb = '';
String webOccupancy = '';
String greyOccupancy = '';
String vannierOccupancy = '';
String libTime = '';
String webLevel = '';
String greyLevel = '';
String vannierLevel = '';

class _HomePageState extends State<HomePage> {
  bool isLoading = true;
  @override
  void initState() {
    super.initState();
    _fetchWebOccupancy();
    _fetchVannierOccupancy();
    _fetchGreyOccupancy();
    _fetchLibTime();
  }

  Future<void> _fetchLibTime() async {
    if (libTime == '') {
      String? libraryTime = await getDataAPI_time().getPosts();
      setState(() {
        libTime = libraryTime.toString();
      });
    }
  }

  Future<void> _fetchWebOccupancy() async {
    if (webOccupancy == '') {
      String? occupancy = await getDataAPI().getPosts();
      setState(() {
        webOccupancy = occupancy!.substring(0, occupancy.length - 5);
        if (webOccupancy == '' || int.parse(webOccupancy) < 0) {
          webOccupancy = '0';
        }
        if (int.parse(webOccupancy) > 100) {
          webLevel = 'High';
        } else if (int.parse(webOccupancy) > 75 &&
            int.parse(webOccupancy) < 100) {
          webLevel = 'Medium';
        } else {
          webLevel = 'Low';
        }
        isLoading = false;
      });
    }
  }

  Future<void> _fetchGreyOccupancy() async {
    if (greyOccupancy == '') {
      String? occupancy = await getDataAPI_G().getPosts();
      setState(() {
        greyOccupancy = occupancy!.substring(0, occupancy.length - 5);
        if (greyOccupancy == '' || int.parse(greyOccupancy) < 0) {
          greyOccupancy = '0';
        }
        if (int.parse(greyOccupancy) > 100) {
          greyLevel = 'High';
        } else if (int.parse(greyOccupancy) > 50 &&
            int.parse(greyOccupancy) < 100) {
          greyLevel = 'Medium';
        } else {
          greyLevel = 'Low';
        }
        isLoading = false;
      });
    }
  }

  Future<void> _fetchVannierOccupancy() async {
    if (vannierOccupancy == '') {
      String? occupancy = await getDataAPI_V().getPosts();
      setState(() {
        vannierOccupancy = occupancy!.substring(0, occupancy.length - 5);
        if (vannierOccupancy == '' || int.parse(vannierOccupancy) < 0) {
          vannierOccupancy = '0';
        }
        if (int.parse(vannierOccupancy) > 100) {
          vannierLevel = 'High';
        } else if (int.parse(vannierOccupancy) > 50 &&
            int.parse(vannierOccupancy) < 100) {
          vannierLevel = 'Medium';
        } else {
          vannierLevel = 'Low';
        }
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        // elevation: 15,
        // leading: IconButton(
        //   icon: const Icon(Icons.menu),
        //   onPressed: () {},
        // ),

        title: const Text('xConcordia'),
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            boxShadow: [
              BoxShadow(
                color: Color.fromARGB(223, 57, 25, 163),
                offset: Offset(0, 0),
                blurRadius: 20,
              ),
            ],
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [Colors.blue, Colors.purple],
            ),
          ),
        ),
      ),
      body: isLoading
          ? const Center(
          child: LinearProgressIndicator(
            color: Color.fromARGB(162, 114, 68, 251),
          ))
          : Container(
        margin: const EdgeInsets.only(top: 20),
        child: Column(
          children: [
            // ignore: prefer_const_constructors
            LibraryStatsHeader(), //LibraryStatsHeader widget is in a file called libraryStatsHeader
            const Padding(padding: EdgeInsets.all(10)),
            libCards(), //libCards widget is in a file called libraryCards
            const categoryPicker(), //category picker
            
          ],
        ),
      ),
      
    );
  }
}

不要将bottomNavigation添加到页面列表中,如homePage()、secondRoute()等。

ie3xauqp

ie3xauqp2#

在Scaffold中尝试此操作

return Scaffold(
  body: screens.elementAt(currentIndex),
  bottomNavigationBar: BottomNavyBar(

删除底部导航栏:const navBar()来自主页
调用main.dart文件的home中的navBar类,如下所示

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return const MaterialApp(
  title: 'Flutter Demo',
  debugShowCheckedModeBanner: false,
  home: navBar(), <------ here
 );
}
}

相关问题