How to use data in another dart class?
In Flutter, you can pass data from one Dart class to another using constructor parameters
First Example:-
// FirstPage.dart
class FirstPage extends StatelessWidget {
final String data;
FirstPage({Key key, @required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Page'),
),
body: Center(
child: Text(data),
),
);
}
}
// SecondPage.dart
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
String data = 'Hello, World!';
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FirstPage(data: data),// here data
// value is pass
),
);
},
child: Text('Go to First Page'),
),
),
);
}
}
// MyApp.dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: SecondPage(),
);
}
}
In this example, the SecondPage has a button that navigates to the FirstPage and passes the data parameter through its constructor. The FirstPage receives the data and displays it in the UI.
Second Example :-
// FirstPage.dart
class FirstPage extends StatelessWidget {
final String data;
FirstPage({Key key, @required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Page'),
),
body: Center(
child: TextField(
controller: TextEditingController(text: data),
decoration: InputDecoration(
labelText: 'Enter Data',
),
),
),
);
}
}
// SecondPage.dart
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
String data = 'Hello, World!';
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FirstPage(data: data),
),
);
},
child: Text('Go to First Page'),
),
),
);
}
}
// MyApp.dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: SecondPage(),
);
}
}
In this example, the SecondPage has a button that navigates to the FirstPage and passes the data parameter through its constructor. The FirstPage receives the data and sets it as the initial value of a TextField.