I have a button in a page. and a class named MySdClass. In my main class i have a constructor that receive some data from MySdClass. i want wen user click on button the constructor of that page receive data from MySdClass again. The code I imagine in my mind does not work:
import 'package:flutter/material.dart';
import 'package:./SdClass.dart';
void main(){
runApp(MainClass(inputData: MySdClass.data,));
}
class MainClass extends StatelessWidget {
final String data;
const MainClass({Key? key, required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
const Text(this.widget.data),
),
ElevatedButton(onPressed: (){//what should be here?}, child: const
Text('next')),
],
);
}
}
CodePudding user response:
void main(){
runApp(MainClass(inputData: MySdClass.data, onPressed:(){
"Perform some action and you can send data again through this contructor"
});
}
class MainClass extends StatelessWidget {
final String data;
void Function() onPressed;
MainClass({Key? key, required this.data,required this.onPressed}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
const Text(this.widget.data),
),
ElevatedButton(onPressed: onPressed, child: const
Text('next')),
],
);
}
}
CodePudding user response:
you could set variable and use it like this:
class MainClass extends StatefulWidget {
final String data;
MainClass({Key key, @required this.data}) : super(key: key);
@override
State<MainClass> createState() => _MainClassState();
}
class _MainClassState extends State<MainClass> {
String _data;
@override
void initState() {
super.initState();
_data = widget.data;
}
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
child: Text(this.widget.data),
),
ElevatedButton(
onPressed: () {
setState(() {
_data = MySdClass.data;
});
},
child: const Text('next')),
],
);
}
}