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?

componentに親Viewから値を渡そうとしたらdon't put any logic in stateで怒られた

Posted at

親ViewのinitStateでAPIから情報を取得して、componentsのCustomCarouselにバナー情報を渡したい

初期化するときにthis.bannersを必ず受け取るようにして、_CustomCarouselState()の引数にbannersをセットすることで情報を渡せば出来るんじゃないの?って思ったら
Don't put any logic in stateというエラーが発生して怒られました

あれ?stateに渡すにはどうしたらいいの?というかそもそも実装の方針が間違ってる?

class CustomCarousel extends StatefulWidget {
  const CustomCarousel({
    super.key,
    required this.banners,
  });
  final List<HomeCarouselBanner> banners;

  @override
  State<CustomCarousel> createState() => _CustomCarouselState();
}

class _CustomCarouselState extends State<CustomCarousel> {
  final List<HomeCarouselBanner> banners = [];
  // bannersにbannersを入れようとした

コンストラクタの中でフィールドを定義してあげて、stateの中でlate修飾子をつけるのが正解だったようです。あとbannersはwidgetのbannersであることを明示的に示す。

lateを付ける理由としては、DartのNull Safety対策で、lateをつけることによって、後から値が入ってくるよってことを教えてあげる必要があるから

class CustomCarousel extends StatefulWidget {
  const CustomCarousel({
    super.key,
    required this.banners, // 追加
  });

  final List<HomeCarouselBanner> banners; //追加
  @override
  State<CustomCarousel> createState() => _CustomCarouselState();
}

class _CustomCarouselState extends State<CustomCarousel> {
  late final banners = widget.banners; //追加 

コンパイルはこれで通って、最初の問いに関してはwidgetのbannersと書くことで値を受け渡せるようです。ただlateを使う方法は絶対ベストプラクティスではないと思う。もうちょっと勉強せねば

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?