1
0

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 1 year has passed since last update.

【Flutter】戻ると画面がリビルドされてしまう

Posted at

Flutterで次のような操作をした時に、戻るボタンタップの後にページAがリビルドされてしまうという問題にハマりました。

ページA→ページB→ページC→戻るタップ→ページB

原因としてはページA→ページBの時にmaintainState: falseを指定していたことでした。

Navigator.of(context).push(MaterialPageRoute(
    builder: (_) => MyHomePage(id: widget.id + 1),
    maintainState: false)); // falseだと戻るでリビルドされる

ドキュメントによるとmaintainStateの説明は次のようになっていました。

Whether the route should remain in memory when it is inactive.
ルートがアクティブでなくなってもメモリに維持するかどうか

true:維持する場合は、メモリにあるのでリビルドされない。false維持しない場合はメモリにないのでリビルドされる。
ということだと理解しました。

おそらくページB以降でページAに関わるステータスが変更された時に、表示を更新したくてこのように回避していたのかもしれません。

再現コード
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(id: 1),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.id}) : super(key: key);

  final int id;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    print("Page ${widget.id} built!");
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.id.toString()),
      ),
      body: Center(
          child: ElevatedButton(
              child: Text("Open next page"),
              onPressed: () {
                Navigator.of(context).push(MaterialPageRoute(
                    builder: (_) => MyHomePage(id: widget.id + 1),
                    maintainState: false)); // falseだと戻るでリビルドされる
              })),
    );
  }
}
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?