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】並び替え画面への値の受け渡し(Navigator)

0
Posted at

全体の流れ

ShoppingPage → Navigator.push で items を渡す → ReorderPage で並び替え → Navigator.pop で結果を返す → Firestore に保存

1. 画面を開く — 値を渡す

final sortedItems = await Navigator.push<List<ShoppingItem>>(
  context,
  MaterialPageRoute(
    builder: (_) => ReorderPage(
      items: currentItems, // 現在のリストを渡す
    ),
  ),
);

Navigator.push<List<ShoppingItem>> の型指定で、戻り値の型を明示しています。

  1. 受け取る側 — コンストラクタで受け取る
class ReorderPage extends StatefulWidget {
  final List<ShoppingItem> items;
  const ReorderPage({super.key, required this.items});
  @override
  State<ReorderPage> createState() => _ReorderPageState();
}
  1. 編集用にコピーする
    渡されたリストをそのまま編集すると元データが壊れるため、initState でコピーします。
class _ReorderPageState extends State<ReorderPage> {
  late List<ShoppingItem> _items;
  @override
  void initState() {
    super.initState();
    _items = List.from(widget.items); // コピーして編集
  }
}
  1. 結果を返す
    // キャンセル(変更なし)
OutlinedButton(
  onPressed: () => Navigator.pop(context),
  child: const Text('戻る'),
)

// 確定(並び替え結果を返す)

FilledButton(
  onPressed: () => Navigator.pop(context, _items),
  child: const Text('確定'),
)
  1. 戻り値を受け取って保存
if (sortedItems == null) return; // キャンセル時
final orderIds = sortedItems.map((e) => e.id).toList();
await FirebaseFirestore.instance
    .collection('userOrders')
    .doc(uid)
    .set({
  currentCategory.name: orderIds,
}, SetOptions(merge: true));

操作 コード

値を渡す
ReorderPage(items: currentItems)
値を返す
Navigator.pop(context, _items)
キャンセル
Navigator.pop(context) → null
型安全
Navigator.push<List<ShoppingItem>>
まとめ
Navigator.pushでリストを渡し、Navigator.pop(context, result)で並び替え結果を返す。編集前にList.from()でコピーしておくのがポイントです。

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?