【Flutter】Providerライブラリについて

Flutter

備忘録です。

Providerライブラリとは

Flutterアプリケーションにおいて状態管理を簡単に行うためのパッケージで、依存性注入ライブラリの1つです。Providerを使うことで、状態を保持するModelやView Modelを作成し、それをアプリケーションの各部分で共有して利用することができます。

導入方法

flutter pub add provider
provider install | Flutter package
A wrapper around InheritedWidget to make them easier to use and more reusable.

例文

// ignore_for_file: public_member_api_docs, lines_longer_than_80_chars
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

/// これは、プロバイダー + [ChangeNotifier] を使用したデフォルトの Flutter アプリケーションの再実装です。

void main() {
  runApp(
    /// プロバイダは[MyApp]の内部ではなく、その上にあるため、テストは[MyApp]の内部で行われます。
    /// プロバイダーをモックしながら [MyApp] を使用できます。
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => Counter()),
      ],
      child: const MyApp(),
    ),
  );
}

class Counter with ChangeNotifier {
  int _count = 0;

  int get count => _count;

  void increment() {
    _count++;
    notifyListeners();
  }
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Example'),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: const <Widget>[
            Text('You have pushed the button this many times:'),

            /// パフォーマンスの最適化のために別のウィジェットとして抽出されます。
            /// 別のウィジェットとして、[MyHomePage] から独立して再構築されます。
            Count(),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        key: const Key('increment_floatingActionButton'),

        /// `context.watch` の代わりに
        /// `context.read` を呼び出して再構築しないようにします。
        /// [Counter] が変化したとき。
        onPressed: () => context.read<Counter>().increment(),
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Text(
      /// [Counter] が変更されたときに [Count] を再構築します。
      /// そのために `context.watch` を呼び出します。
      '${context.watch<Counter>().count}',
      key: const Key('counterState'),
      style: Theme.of(context).textTheme.headlineMedium,
    );
  }
}
provider example | Flutter package
A wrapper around InheritedWidget to make them easier to use and more reusable.

Buy me a coffee!

Flutterアプリ開発
シェアする
sogaをフォローする
タイトルとURLをコピーしました