0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Flutter初心者がState管理で混乱した話 🌀

Posted at

はじめに

こんにちは!Flutter初心者の私ですが、アプリ改修の仕事をする中でまたまたにつまずいたのが State管理 でした。

「setState?」「StatelessWidgetとStatefulWidgetの違い?」「なんで画面が更新されないの?😭」
まさに混乱の連続でした…。

この記事では、私が State管理で迷子になったエピソード と、そこから学んだことをまとめます。


📚目次


❌ 最初にやらかしたこと:画面が更新されない 😭

最初に出会ったのが「ボタンを押しても画面が変わらない」という謎現象。

class CounterPage extends StatelessWidget {
  int counter = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $counter'),
        ElevatedButton(
          onPressed: () {
            counter++;
          },
          child: const Text('Increment'),
        ),
      ],
    );
  }
}

👉 ボタンを押しても 表示は変わらない。
理由はシンプルで「StatelessWidgetは状態を持たない」からでした😇

😅 改善1:StatefulWidgetに書き直す ✍️

次に試したのがこちら👇

class CounterPage extends StatefulWidget {
  const CounterPage({super.key});

  @override
  State<CounterPage> createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  int counter = 0;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $counter'),
        ElevatedButton(
          onPressed: () {
            setState(() {
              counter++;
            });
          },
          child: const Text('Increment'),
        ),
      ],
    );
  }
}

👉 setState を使えばちゃんとUIが更新される!🎉

でもここで「setStateってどこでも使っていいの?」と疑問が生まれました🤔

✅ 学び:Stateは「どこで管理するか」が大事 🗝️

最終的に理解したのは、

「UIに変化があるデータはStateに置く」

「Stateは必要な範囲だけに絞る」

「大きなアプリではProviderやRiverpodなどを検討する」

ということでした。

👉 最初から完璧にやろうとしなくてもOK。
「まずはsetStateで動かす → 管理が大変になってから状態管理パッケージを検討する」で十分だと気づきました✨

💡 まとめ:State管理で迷子にならないための心得

UIが変わるならStatefulWidgetを使う

setStateは「どの範囲のUIを更新するか」意識して使う

慣れてきたら状態管理パッケージへステップアップ

おわりに 🌸

FlutterのState管理は最初めちゃくちゃ混乱しましたが、今では「UIと状態をセットで考える」という考え方にすごく納得感があります!
もし「画面が更新されない!😭」と悩んでいる人がいたら、少しでもこの記事がヒントになれば嬉しいです💖

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?