Flutter: Provider を使ったカウンターアプリ

Flutter: Provider を使ったカウンターアプリ

June 3, 2024

こんな感じ。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(const MyApp());
}

class CounterModel extends ChangeNotifier {
  int count = 0;

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChangeNotifierProvider(
        create: (_) => CounterModel(),
        child: const MyPageWidget(),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Column(
        children: [
          MyCountWidget(),
          MyButtonWidget(),
        ],
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    final counter = context.watch<CounterModel>();

    return Text("count: ${counter.count.toString()}");
  }
}

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

  @override
  Widget build(BuildContext context) {
    final counter = context.read<CounterModel>();

    return IconButton(
      icon: const Icon(Icons.add),
      onPressed: () {
        counter.increment();
      },
    );
  }
}