import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:go_transitions/go_transitions.dart';
void main() {
runApp(const MyApp());
}
/// 1. GoRouterの定義
/// パスと画面(Widget)の組み合わせを登録する
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
name: 'home',
path: '/',
builder: (context, state) => const HomeScreen(),
pageBuilder: GoTransitions.slide.toLeft.withFade,
routes: <RouteBase>[
// 詳細画面へのネストされたルート
GoRoute(
name: 'details', // 名前を定義
path: '/details',
builder: (context, state) => DetailScreen(),
pageBuilder: GoTransitions.slide.toLeft.withFade,
),
],
),
],
);
/// 2. MaterialApp.router の設定
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
GoTransition.defaultCurve = Curves.easeInOut;
GoTransition.defaultDuration = const Duration(milliseconds: 600);
return MaterialApp.router(
debugShowCheckedModeBanner: false,
routerConfig: router, title:'GoRouter Test',);
}
}
/// ホーム画面
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.limeAccent,
appBar: AppBar(
title: const Text('Home Screen'),
centerTitle: true,
backgroundColor: Colors.green,//背景色を指定
),
body: Center(
child: ElevatedButton(
// onPressed: () => context.go('/details'),
onPressed: () =>context.goNamed('details'),
// onPressed: () {
// 3. 画面遷移(context.go)
// context.go('/details');
// },
child: const Text('Go to Details'),
),
),
);
}
}
// 詳細画面
class DetailScreen extends StatelessWidget {
const DetailScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Detail Screen'),
centerTitle: true,
backgroundColor: Colors.orange,//背景色を指定
),
body: Center(
child: ElevatedButton(
// onPressed: () {context.pop(); },
// onPressed: () => context.go('/'),
onPressed: () =>context.goNamed('home'),
child: const Text('Back'),
),
),
);
}
}