LoginSignup
4
0

More than 1 year has passed since last update.

[Flutter Web] VRouterを使ってURLからパラメータを取得する

Posted at

この記事は、【 可茂IT塾 Advent Calendar 2021 】の12日目の記事です。

FlutterWebのアプリ作成で実装したことを記事にしました。
誰かのお役に立てれば、幸いです。

VRouterについて

このパッケージは、FlutterWebのルーティングをいい感じにしてくれます。

可茂IT塾のブログでも一度紹介されていて、

ブログでは、hashモードhistoryモードについて解説されています。

ドキュメントにもある、基本的な実装は下のコード例のようになります。

// main.dart

import 'package:flutter/material.dart';
import 'package:vrouter/vrouter.dart';
import 'package:web_test/pages/home_page.dart';
import 'package:web_test/pages/setting_page.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return VRouter(
        debugShowCheckedModeBanner: false,
        mode: VRouterMode.history,
        routes: [
          VWidget(path: '/', widget: const HomePage()),
          VWidget(path: '/setting', widget: const SettingPage()),
        ]);
  }
}

main.dartでVRouterを返して、そこにルーティングを書きます。(routes:の部分)

// home_page.dart

import 'package:flutter/material.dart';
import 'package:vrouter/vrouter.dart';

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("ホームページ")),
      body: ElevatedButton(
        onPressed: () => context.vRouter.to('/setting'),
        child: const Text("セッティングページへ"),
      ),
    );
  }
}


上記のような形で、ページ遷移できます。

動的なルーティングでURLからパラメータを取得する

なにかしらのIDを渡したりして、URLを動的に変化させたい場合は、ルーティングの書き方を少しだけ変える必要があります。

      VWidget(
        path: '/user/:userId',  // ここを変える
        widget: UserScreen(),
      ),

動的な部分にコロンを付けるだけです。

パラメータを反映させたURLを指定して、ページ遷移させます。

ElevatedButton(
   onPressed: () => context.vRouter.to('/user/$userId'), //URLにパラメータを入れる
   child: Text('Go to $user'),
 ),

遷移したページで、このパラメータを取得するには、下のようになります。

final _userId = context.vRouter.pathParameters['userId'];

参考

4
0
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
4
0