はじめに
本記事はFlutter Cookbook - Pass arguments to a named routeと殆ど同じ内容です。
Cookbookに記載されているComplete exampleがonGenerateRoute
関数を使用したものしかなかった為、onGenerateRoute
関数を使用しない版のComlete exampleを記録しています。
実装の手順
- 引数を定義したクラスを作成
- 引数を抽出し、引数を処理するウィジェットを作成
- 2で作成したウィジェットをルートテーブルに設定
- 2で作成したウィジェットに引数を渡しつつ遷移
Comlete example
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Navigation with Arguments',
home: HomeScreen(),
// 3. 2で作成したWidgetをルートテーブルに設定
routes: {
ExtractArgumentsScreen.routeName: (_) => ExtractArgumentsScreen(),
}
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
),
body: Center(
child: RaisedButton(
child: Text("Navigate to screen that extracts arguments"),
onPressed: () {
// 4. ExtractArgumentsScreenに遷移
// argumentsプロパティでScreenArgumentsオブジェクトを生成し、引数を提供
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'First argument',
'Second argument.',
)
);
},
),
),
);
}
}
// 2. 引数を抽出し、引数を処理するWidgetを作成
class ExtractArgumentsScreen extends StatelessWidget {
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {
// `ModalRoute.of()`メソッドを使用して、
// `ScreenArguments('First argument', 'Second argument.')の引数を取得
final ScreenArguments args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
}
// 1. 引数を定義したクラス
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}