📱

Flutterで遷移先で変数の値を更新し、遷移元に返す

2024/09/18に公開

1. 遷移元

first_screen.dart
class FirstScreen extends StatefulWidget {
  
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  String _message = '';

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 遷移先からの値を受け取る
            final result = await Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondScreen()),
            );
            // 受け取った値で変数を更新
            setState(() {
                _message = result;
          });
        },
        child: Text('ボタン'),
     ),
    );
  }
}

2. 遷移先

second_screen.dart
class SecondScreen extends StatelessWidget {
  
  Widget build(BuildContext context) {
    String _value = '';

    return Scaffold(
      body: Center(
        child: TextField(
          onChanged: (value) {
            _value = value;
          },
          decoration: InputDecoration(
            hintText: 'メッセージを入力してください',
          ),
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: () {
            // 入力した値を遷移元に渡して戻る
            Navigator.pop(context, _value);
          },
          child: Text('戻る'),
        ),
      ),
    );
  }
}

Discussion