2
2

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.

StateNotifierProviderとbuilderの最小構成

Last updated at Posted at 2020-06-02

flutter_state_notifier 0.4.0から、 StateNotifierProviderに新しくbuilderというパラメーターが追加されました。

それを使うと、Providerを定義したすぐ下で、context.readやcontext.selectが使えて便利です。

以下はその最小構成です。数字と、それを増やしていくボタンです。

main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:state_notifier/state_notifier.dart';
import 'package:flutter_state_notifier/flutter_state_notifier.dart';

void main() {
  runApp(Demo());
}

class Demo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Demo'),
        ),
        body: Center(child: Home()),
      ),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StateNotifierProvider<CounterNotifier, CounterState>(
      create: (context) => CounterNotifier(),
      builder: (context, child) {
        final count = context.select((CounterState s) => s.count).toString();
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            RaisedButton(onPressed: () {
              context.read<CounterNotifier>().increment();
            }),
            Text(count),
          ],
        );
      },
    );
  }
}

class CounterState {
  CounterState(this.count);
  int count;
}

class CounterNotifier extends StateNotifier<CounterState> {
  CounterNotifier() : super(CounterState(0));

  void increment() {
    state = CounterState(++state.count);
  }
}


2
2
1

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?