カテゴリー
App

Flutterで状態管理あれこれ2

 状態管理の元となるInheritedWidgetを理解するためにカウンターアプリを改造して実装してみましたがとても複雑でした。

 それで流行りのパッケージを実装してみました。使いやすいように InheritedWidget をラップしているのでコードは短くなるのですが、バージョンによって細かく記述方法が異なりなり正解にたどり着くのが大変です。

  flutter_hooks: ^0.17.0
  hooks_riverpod: ^0.14.0+4
  state_notifier: ^0.7.0
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:gap/gap.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

final viewModel = StateNotifierProvider((_) => ViewModel());

class ViewModel extends StateNotifier<int> {
  ViewModel() : super(0);
  void increment() => state++;
  void decrement() => state--;
}

void main() {
  runApp(
    ProviderScope(
      child: CounterApp(),
    ),
  );
}

class CounterApp extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final _viewModel = useProvider(viewModel);

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('CounterApp')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              Text(
                _viewModel.toString(),
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
        floatingActionButton: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            FloatingActionButton(
              heroTag: 'increment',
              onPressed: () => context.read(viewModel.notifier).increment(),
              child: Icon(Icons.add),
            ),
            Gap(15),
            FloatingActionButton(
              heroTag: 'decrement',
              onPressed: () => context.read(viewModel.notifier).decrement(),
              child: Icon(Icons.remove_circle_outline),
            ),
          ],
        ),
      ),
    );
  }
}

 このコードもパッケージのバージョンがちょっとでも上がれば直さなくなると思います。

Flutterで状態管理あれこれ2
Flutterで状態管理あれこれ2

実機のスクリーンショットは
flutter screenshot
で撮れます。プロジェクトフォルダーに画像が保存される。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です