😊
FlutterにおけるGoRouterの使い方
1. 基本的なルート定義
Flutterのgo_routerパッケージを使うと、簡単にルーティングを管理できます。基本的なルートの定義は以下のようになります。
dart
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomeScreen(),
),
GoRoute(
path: '/detail',
builder: (context, state) => DetailScreen(),
),
],
);
この場合、/ にアクセスすると HomeScreen が、/detail にアクセスすると DetailScreen が表示されます。
2. クエリパラメータを使った値の受け渡し
画面遷移時にパラメータを渡すには、クエリパラメータを使う方法があります。
ルートの定義
dart
GoRoute(
path: '/profile',
builder: (context, state) {
final userId = int.tryParse(state.uri.queryParameters['user_id'] ?? '') ?? 0;
return ProfileScreen(userId: userId);
},
),
遷移時のURL
dart
context.go('/profile?user_id=42');
値の受け取り
ProfileScreen で userId を受け取り、適切に処理できます。
dart
class ProfileScreen extends StatelessWidget {
final int userId;
const ProfileScreen({super.key, required this.userId});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('User Profile')),
body: Center(
child: Text('User ID: $userId'),
),
);
}
}
3. パスパラメータを使った値の受け渡し
クエリパラメータの代わりに、パスパラメータを使う方法もあります。
ルートの定義
dart
GoRoute(
path: '/product/:id',
builder: (context, state) {
final productId = int.tryParse(state.pathParameters['id'] ?? '') ?? 0;
return ProductScreen(productId: productId);
},
),
遷移時のURL
dart
context.go('/product/100');
値の受け取り
ProductScreen で productId を取得できます。
dart
class ProductScreen extends StatelessWidget {
final int productId;
const ProductScreen({super.key, required this.productId});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product Detail')),
body: Center(
child: Text('Product ID: $productId'),
),
);
}
}
まとめ
-
context.go() はルートを置き換え、context.push() は新しい画面をスタックに追加する。
-
クエリパラメータ (?key=value) やパスパラメータ (/:value) を使って値を渡せる。
GoRouterを活用して、スムーズな画面遷移を実装しましょう!
Discussion