flutter学習中です。
テーマ、知りたいこと
任意の画面の初回描画時のみ処理を書いていますが(ボタンを押した後は実行されない)、こういった際は、StatefulWidgetのinitState()を使用するのが一般的でしょうか?
又、他に選択肢はあるのでしょうか?
背景
色々なサイトで学習していると現在はriverpodを使用するのが主流と書いてあり、StatefulWidgetはあまり使わないと書いてます。riverpodで書く事は出来るのでしょうか?また、riverpod(他の方法でも)に置き換えることは妥当なのでしょうか?
状況
念の為に、下にコードも出します。簡略化しているので動作しなければご容赦下さい。
CRUD対応のツイッター的なアプリを作っています。
*入力画面から遷移して来る
*初回描画にfirestoreにデータを作成。
*登録完了を表示
*ボタンを押して一覧画面へ遷移
このコードの中でinitState()を使用しないと、初回描画とボタンを押した際で2回
await db.collection('tweets').doc().set(
{
'userName': widget.tweet_username,
'text': widget.tweet_text,
},
が実行されてしまいました。
よろしくお願いします。
dart
1import 'package:flutter/material.dart';2import 'package:cloud_firestore/cloud_firestore.dart';3 4class TweetAddexec extends StatefulWidget {5 final String tweet_username;6 final String tweet_text;7 8 const TweetAddexec({9 Key? key,10 required this.tweet_username,11 required this.tweet_text,12 }) : super(key: key);13 14 15 _TweetAddexecState createState() => _TweetAddexecState();16}17 18class _TweetAddexecState extends State<TweetAddexec> {19 20 void initState() {21 super.initState();22 23 final db = FirebaseFirestore.instance;24 await db.collection('tweets').doc().set(25 {26 'userName': widget.tweet_username,27 'text': widget.tweet_text,28 },29 );30 }31 32 33 Widget build(BuildContext context) {34 return Scaffold(35 backgroundColor: Colors.orange,36 appBar: AppBar(37 title: Text('登録完了'),38 automaticallyImplyLeading: false,39 ),40 floatingActionButton: FloatingActionButton(41 onPressed: () => GoRouter.of(context).push('/tweet/index'),42 child: const Text('一覧画面へ'),43 ),44 );45 }46}47

0 コメント