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】shared_preferencesを使って初回起動の時だけチュートリアル画面を表示させる

Posted at

はじめに

アプリを始めて起動したユーザーだけにチュートリアル画面を見せたい!という場合はよくあるかと。
一番簡単に実装する方法としては、おそらくshared_preferencesを使う方法かと思います。

shared_preferencesはデータを端末のローカルに保存するためのパッケージです。
ローカルに「チュートリアル画面を開いたらtrueにする」というような値を保存して、falseの場合のみチュートリアル画面を表示すれば、
初回起動の時だけチュートリアル画面を表示させる」が実現できます。

main.dart

以下shared_preferencesはインストール済みの前提で進めます!

lib/main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final prefs = await SharedPreferences.getInstance();
  // 初回起動の時でfirst_launchが存在しなければtrueになる
  bool firstLaunch = prefs.getBool('first_launch') ?? true;
  runApp(ProviderScope(
    child: MyApp(
      firstLaunch: firstLaunch,
    ),
  ));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key, required this.firstLaunch});
  final bool firstLaunch;

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // 初回起動の場合(つまりローカルにfirst_launchが存在しない場合)はIntroductionScreenになる
      home: firstLaunch ? const IntroductionScreen() : const StartScreen(),
    );
  }
}

チュートリアル画面

チュートリアル画面のビルドメソッドや、特定のボタンを押した時(例えば完了など)に以下のような処理でfirst_launchfalseに設定することができればOK!

  _saveOptions() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // 一度起動したらfirst_launchをfalseに設定する
    await prefs.setBool('first_launch', false);
  }

これで次からはローカルにfirst_launchfalseで存在するので、チュートリアル画面に遷移せずにStartScreenへ遷移します:muscle_tone2:

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?