リスト追加できるようにする(画面遷移時の値受け渡し)

createPageの修正

import 'package:flutter/material.dart';

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

  @override
  State<CreatePage> createState() => _CreatePageState();
}

class _CreatePageState extends State<CreatePage> {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('新規Todo追加'),
        backgroundColor: Colors.cyan,
      ),
      body: Padding(
        padding: const EdgeInsets.all(32.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                labelText: 'Todoを入力',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: () {
                if (_controller.text.isNotEmpty) {
                  Navigator.of(context).pop(_controller.text);
                }
              },
              child: Text("追加"),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text("キャンセル"),
            ),
          ],
        ),
      ),
    );
  }
}

TodoPageの修正

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

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

  @override
  State<TodoPage> createState() => _TodoPageState();
}

class _TodoPageState extends State<TodoPage> {
  List<String> todos = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.cyan,
        title: Text(
          'Todo List',
          style: TextStyle(
            color: Colors.white,
            fontSize: 24.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: todos.isEmpty
          ? Center(
              child: Text(
                'Todoはありません',
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
            )
          : ListView.builder(
              itemCount: todos.length,
              itemBuilder: (context, index) => ListTile(
                title: Text(todos[index]),
              ),
            ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.cyan,
        foregroundColor: Colors.white,
        onPressed: () async {
          // CreatePageから値を受け取る
          final newTodo = await Navigator.of(context).push<String>(
            MaterialPageRoute(builder: (context) => CreatePage()),
          );
          if (newTodo != null && newTodo.isNotEmpty) {
            setState(() {
              todos.add(newTodo);
            });
          }
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

1. Todoリスト(todos)の管理


2. Todoの追加方法

final newTodo = await Navigator.of(context).push<String>(
  MaterialPageRoute(builder: (context) => CreatePage()),
);

3. Todoリストへの反映

if (newTodo != null && newTodo.isNotEmpty) {
  setState(() {
    todos.add(newTodo);
  });
}