The app is supposed to take in the first name on the first page and reverse it, then print the output on the second page. I'm having trouble implementing the output from the _incrementCounter method into the SecondScreen class in order to print the output on the second page.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext ctxt) {
return MaterialApp(
home: FirstScreen(),
);
}
}
class FirstScreen extends StatelessWidget {
String t1 = '', output = '';
RevName name = RevName();
void _incrementCounter() {
setState(() {
output = name.reverseName(t1) as String;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(child: Text("Reverse Name")),
),
body: Column(
children: [
Padding(
padding: EdgeInsets.all(20.0),
child: TextField(keyboardType: TextInputType.name,
decoration: const InputDecoration(
labelText: 'Enter Your First Name',
border: OutlineInputBorder()),
onChanged: (text) {
t1 = text;
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: OutlinedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen()),
);
_incrementCounter();
},
child: Text('Reverse Name'),
),
),
],
)
);
}
void setState(Null Function() param0) {}
}
class SecondScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Reverse Name"),
),
body: Column(
children: [
Center(
child: OutlinedButton(
onPressed: (){
Navigator.pop(context);
},
child: Text('Back')
),
),
],
)
);
}
}
The class where name is being reversed and returning the reversed name
class RevName {
String name, reversed;
RevName({this.name = '', this.reversed = ''});
String reverseName(name) {
reversed = name.split('').reversed.join('');
return '$reversed';
}
}
CodePudding user response:
You've RevName
model class, to store name and reverse name. You can modify like,
class RevName {
String name, reversed;
RevName({
required this.name,
}) : reversed = name.split('').reversed.join('');
}
Now let's pass data using constructor. Remove state RevName
and follow this,
child: OutlinedButton(
onPressed: () {
RevName revName = RevName(name: t1);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(
data: revName,
),
),
);
},
child: const Text('Reverse Name'),
),
On receiver side SecondScreen
.
class SecondScreen extends StatelessWidget {
final RevName data;
const SecondScreen({
Key? key,
required this.data,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Reverse Name"),
),
body: Column(
children: [
Text(data.name),
Text(data.reversed),
You can follow this answer to explore alternative way.