LoginSignup
13
9

More than 3 years have passed since last update.

Named routeに引数を渡すサンプルコード

Last updated at Posted at 2019-09-18

はじめに

本記事はFlutter Cookbook - Pass arguments to a named routeと殆ど同じ内容です。

Cookbookに記載されているComplete exampleがonGenerateRoute関数を使用したものしかなかった為、onGenerateRoute関数を使用しない版のComlete exampleを記録しています。

実装の手順

  1. 引数を定義したクラスを作成
  2. 引数を抽出し、引数を処理するウィジェットを作成
  3. 2で作成したウィジェットをルートテーブルに設定
  4. 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);
}
13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9