randomuser1
randomuser1

Reputation: 2803

why does my bottomnavigationbar doesn't work in flutter?

I created a simple code that contains the bottomnavigationbar in Flutter, but it doesn't work. My code is as follows:

class MainPage extends StatefulWidget{
  @override
  DashboardScreen createState() {
    return DashboardScreen();
  }
}

class DashboardScreen extends State<MainPage> {

Widget callPage(int currentIndex) {
    switch (currentIndex) {
      case 0 : return MainPage();
      case 1 : return SecondPage();
      case 2 : return ThirdPage();
      break;
      default:  MainPage();
    }
  }

  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dashboard',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Dashboard'),
        ),
        body: callPage(_currentIndex),
    bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
              backgroundColor: Colors.blue
          ),
          BottomNavigationBarItem(
              icon: Icon(Icons.settings),
              label: 'Settings',
              backgroundColor: Colors.blue
          ),
          BottomNavigationBarItem(
              icon: Icon(Icons.account_circle),
              label: 'Profile',
              backgroundColor: Colors.blue
          )
        ],
        onTap: (index) {
            setState((){
              _currentIndex = index;
              print(_currentIndex);
              print("setstate");
            });

        },
      ),
      )
    );
  }

But now, when I deploy it to the android emulator, I'm getting the following error:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════ Stack Overflow The relevant error-causing widget was: MaterialApp file:///Users/user/AndroidStudioProjects/myapp/lib/dashboard.dart:34:12 ════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════ 'package:flutter/src/widgets/framework.dart': Failed assertion: line 4345 pos 14: 'owner._debugCurrentBuildTarget == this': is not true. The relevant error-causing widget was: MaterialApp file:///Users/user/AndroidStudioProjects/myapp/lib/dashboard.dart:34:12

and the 34th line is this:

return MaterialApp(

This error keeps appending in the console until I disconnect from the device. Why so and how can I make my bottomnavigationbar working? Thanks!

Upvotes: 0

Views: 1446

Answers (1)

Marcos Boaventura
Marcos Boaventura

Reputation: 4741

A little bit trick your code but the reason of the failure is because the MainPage widget is returning itself recursively. I did refactoring the code and I got it running in dartpad. You can copy, paste and run the code there.

The comments will show you the pitfalls.

import 'package:flutter/material.dart';

// Just the app startup
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MainPage(),
    );
  }
}

// === The main part starts here!

class MainPage extends StatefulWidget{
  @override
  DashboardScreen createState() {
    return DashboardScreen();
  }
}

class DashboardScreen extends State<MainPage> {

Widget callPage(int currentIndex) {
    switch (currentIndex) {
      case 0 : return Container(color: Colors.red); // MainPage() // why? it's
// returning the same widget again recursively...
      case 1 : return Container(color: Colors.blue); // SecondPage()
      case 2 : return Container(color: Colors.green); // ThirdPage()
      break;
      default:  return Container(color: Colors.amber); // HomePage() same mistake here
    }
  }

  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Dashboard'),
        ),
        body: callPage(_currentIndex),
    bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        items: [
          BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
              backgroundColor: Colors.blue
          ),
          BottomNavigationBarItem(
              icon: Icon(Icons.settings),
              label: 'Settings',
              backgroundColor: Colors.blue
          ),
          BottomNavigationBarItem(
              icon: Icon(Icons.account_circle),
              label: 'Profile',
              backgroundColor: Colors.blue
          )
        ],
        onTap: (index) {
          setState((){
              _currentIndex = index;
              print(_currentIndex);
              print("setstate");
            });

        },
      ),
    );
  }
}

Upvotes: 1

Related Questions