📲
Flutterで画面遷移を実装したらエラーになった
エラー文
Exception has occurred.
FlutterError (Navigator operation requested with a context that does not include a Navigator.
The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.)
主な原因:
・MaterialAppの外でナビゲーション操作を試みている
・Builderウィジェットなしで直接MaterialApp内でナビゲーション操作を試みている
以下、実際にエラーになった文章
import 'package:flutter/material.dart';
import 'package:nekospot_app/home_page.dart';
class TitlePage extends StatelessWidget {
const TitlePage({super.key});
Widget build(BuildContext context) {
return MaterialApp( // エラーの原因
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'テストApp',
style: TextStyle(
fontSize: 32.0,
fontWeight: FontWeight.bold,
color: Colors.pink[200],
letterSpacing: 1.5,
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
},
style: ElevatedButton.styleFrom(
textStyle: TextStyle(
letterSpacing: 1.5,
),
),
child: Text('はじめる',
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontWeight: FontWeight.bold,
letterSpacing: 1.5,
)),
),
],
),
),
),
);
}
}
結論
画面遷移先にMaterialAppを書いてはいけないと言うことです。
MaterialApp クラスについて
Discussion