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

Flutterでglobalに使用できるcontextの作り方

Posted at

NavigatorKey

概要

NavigatorKeyはグローバルなBuildContextを取得したい場合に使用する。
主にUIに依存しないダイアログなどを作成する場合に役に立つ。

実装

まずグローバルでNavigatorKeyを宣言する。

import 'package:flutter/material.dart';

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

次にMaterialApp内でNavigatorKeyをプロパティとして渡す。
大抵このウィジェットはmain.dart内にある。

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: APP_THEME_DATA,
      navigatorKey: navigatorKey, //ここを追加
      home: const MyHomePage(),
    );
  }
}

これでnavigatorKeyを使用してBuildContextなしでcontextを取得できるようになった。
書き方はnavigatorKey.currentState!である。
以下はその例。
BuildContext引数なしでcontextを取得することができている。

showWarnDialog(){
  showDialog(
    context: navigatorKey.currentContext!,
    builder: (BuildContext context){
      return ... ;
    } 
  );
0
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
0
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?