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.
You are getting an infinite loop because you are calling MainApp again and again. The mistake is here: the
initialRouteis/mainand/mainis pointing to MainApp and so on. to fix it, you should create a HomePage or FirstPage for app and pass it as your/mainroute.here is a working code for your case: