我如何通过pop()传递参数到上一个屏幕?



在屏幕上,用户在字段中输入一条消息,当单击按钮时,pop()触发。我如何将数据从字段传递到前一个屏幕并显示它?为了实现,我需要使用pop()Screen with TextField:

// text controller for message input
TextEditingController textController = TextEditingController();
@override
void dispose() {
textController.dispose();
super.dispose();
}
// go to result screen
void getResult() {
Navigator.pop(context, textController.text);
}

ElevatedButton(
onPressed: getResult, child: const Text('Display result'))

ResultScreen:

class ResultScreen extends StatefulWidget {
@override
State<ResultScreen> createState() => _ResultScreenState();
}
class _ResultScreenState extends State<ResultScreen> {
@override
Widget build(BuildContext context) {
// navigation to text_screen
void _navToTextScreen() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const TextScreen()),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Results'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _navToTextScreen,
child: const Text('Enter data'),
),
const SizedBox(
height: 50
),
Text('User Message:'),
const SizedBox(
height: 20
),
],
)),
);
}
}

等待弹出和结果

Future<void> _navToTextScreen() async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const TextScreen()),
);

这是一个有效的概念证明:

import 'package:flutter/material.dart';
class FirstWidget extends StatefulWidget {
const FirstWidget({Key? key}) : super(key: key);
@override
State<FirstWidget> createState() => _FirstWidgetState();
}
class _FirstWidgetState extends State<FirstWidget> {
String text = 'Hello';
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(text),
//textbutton widget that waits for value from a new page, and when it's popped and sets it to the variable 'text'.
TextButton(
child: const Text('Click me'),
onPressed: () async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const FooWidget(),
),
);
setState(() {
text = result;
});
},
),
],
);
}
}
class FooWidget extends StatelessWidget {
const FooWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return
//text widget that passes it's value to the previous page.
Column(
children: [
const Text('Hello'),
TextButton(
child: const Text('Click me'),
onPressed: () {
Navigator.pop(context, 'Hello from FooWidget');
},
),
],
);
}
}

最新更新