43
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Flutter]画面遷移のやり方

Posted at

「Navigate to a new screen and back」を使った画面遷移

(1). ボタンを作成

      body: Center(
        child: RaisedButton(
          child: Text('次へ'),
          onPressed: (){
            // 押したら反応するコードを書く
            // 画面遷移のコード
          },
        ),
      ),

(2). 遷移先のページを作成

import 'package:flutter/material.dart';

class NextPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("次のページ"),
      ),
      body: Container(
        height: double.infinity,
        color: Colors.red,
      ),
    );
  }
}

(3). (1)で作成したボタンに「押下したらページ遷移」の処理を追加
*「NextPage()」の部分に次ページのclassを書く

      body: Center(
        child: RaisedButton(
          child: Text('次へ'),
          onPressed: (){
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => NextPage(),
              )
            )
          },
        ),
      ),

(4). (2)で作成したクラスに「1つ前のページに戻る」処理を加えたボタンを作成

      body: Container(
        height: double.infinity,
        color: Colors.red,
        child: Center(
          child: RaisedButton(
            child: Text('戻る'),
            onPressed: (){
              // 1つ前に戻る
              Navigator.pop(context);
            },
          ),
        ),
      ),

「Navigate with named routes」を使った画面遷移

(1). 初期画面にinitialRoute, routesを設定
*homeを指定してはいけない
*initialRouteに指定しているものが初期画面となる

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: '/',
      routes: {
        // 初期画面のclassを指定
        '/': (context) => MyHomePage(),
        // 次ページのclassを指定
        '/next': (context) => NextPage(),
      },
    );
  }
}

(2). 「押下したらページ遷移」の処理を追加

      body: Center(
        child: RaisedButton(
          child: Text('次へ'),
          onPressed: (){
            Navigator.pushNamed(context, '/next');
          },
        ),
      ),
43
32
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
43
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?