Error with route navigation in Flutter. Invalid argument: Maximum call stack size exceeded

31 Views Asked by At

I'm trying to learn how to navigate between pages in Flutter. I developed a very simple application but it is producing an error. Codeium is saying it is caused by an infinite loop create by the routes placement but won't tell me how to fix it. There are two pages

Here is the main page

import 'package:flutter/material.dart';
import 'package:flutter_application_3/secondpage.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute:'/main',
    routes: {
      '/main': (context) => const MainApp(),
      '/secondpage': (context) => const SecondPage(),
    },
      home: Scaffold(
        appBar: AppBar(
          title: const Text('First Page'),
        ),
        body:(
          ElevatedButton(
              onPressed: () {
            Navigator.pushNamed(
              context,'/secondpage');
              },
              child: const Text('Go to second page'),
            )
          ),
          
        ),
      );
    
  }
}

Here is the second page

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Second Page')),
      
    );
  }
}

Thanks for any help.

1

There are 1 best solutions below

0
Zahra On

You are getting an infinite loop because you are calling MainApp again and again. The mistake is here: the initialRoute is /main and /main is pointing to MainApp and so on. to fix it, you should create a HomePage or FirstPage for app and pass it as your /main route.

here is a working code for your case:

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/main',
      routes: {
        '/main': (context) => const FirstPage(),
        '/secondpage': (context) => const SecondPage(),
      },
      home: const FirstPage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('First or Home Page')),
      body: (ElevatedButton(
        onPressed: () {
          Navigator.pushNamed(context, '/secondpage');
        },
        child: const Text('Go to second page'),
      )),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Second Page')),
    );
  }
}