🎃

Riverpod 1.0.3 + state_notifierで作るBottomNavigationBarを用いた下タブナビゲーション

2021/12/28に公開約2,200字

はじめに

タイトルの通りです。hooks_riverpod(Riverpod)Ver 1.0.3 + state_notifierで作っている記事が見当たらなかったので、備忘録的に置いておきます。

作ったもの

使用ライブラリ

pubspec.yaml
dependencies:

  hooks_riverpod: ^1.0.3
  state_notifier: ^0.7.1
dev_dependencies:

  build_runner: ^2.1.7
  freezed: ^1.1.0

コード

このコミットを見てください!

https://github.com/dl10yr/zenn_flutter/commit/30c55507b1cf0069c4f7321bc635fda27708f65a

state

bottom_navigation_bar_state.dart
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'bottom_navigation_bar_state.freezed.dart';

enum BottomTabItem { tabA, tabB, tabC }


abstract class BottomNavigationBarState with _$BottomNavigationBarState {
  factory BottomNavigationBarState({
    (BottomTabItem.tabA) final BottomTabItem viewItem,
  }) = _BottomNavigationBarState;
}

provider

bottom_navigation_bar_provider.dart
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:zenn_flutter/state/bottom_navigation_bar_state.dart';

class BottomNavigationBarNotifier
    extends StateNotifier<BottomNavigationBarState> {
  BottomNavigationBarNotifier() : super(BottomNavigationBarState());

  void select(BottomTabItem newItem) {
    state = state.copyWith(viewItem: newItem);
  }
}

final bottomNavigationBarProvider = StateNotifierProvider<
    BottomNavigationBarNotifier, BottomNavigationBarState>((_) {
  BottomNavigationBarNotifier notify = BottomNavigationBarNotifier();
  return notify;
});

page

bottom_navigation_bar_view.dart
  
  Widget build(BuildContext context, WidgetRef ref) {
    final bottomTabState = ref.watch(bottomNavigationBarProvider);
    final bottomTabNotifier = ref.watch(bottomNavigationBarProvider.notifier);
    return MaterialApp(
      home: Scaffold(
        bottomNavigationBar: BottomNavigationBar(
          ...
          onTap: (int selectIndex) {
            bottomTabNotifier.select(_items[selectIndex]); // BottomNavigationBarNotifierのselect呼んで切り替えてる
          },

コマンド等

flutter pub run build_runner build --delete-conflicting-outputs

References

https://zuma-lab.com/posts/flutter-bottom-navigation-bar-with-riverpod

Discussion

ログインするとコメントできます