How do i access a varible from another class in Flutter - flutter

I'm making my first flutter app.
it asks for some information then when you click a button it shows the information you entered on another page, I wanted to ask. How do I get a variable from another class?
so I can use the information entered on another page

It seems like you want to pass some data while navigating to another page. If I'm not wrong You should define a variable in the destination like this:
class NewPage extends StatefulWidget {
final int someInt;
NewPage({Key key, this.someInt}) : super(key: key);
#override
_NewPageState createState() => _NewPageState();
}
class _NewPageState extends State<NewPage> {
#override
Widget build(BuildContext context) {
return Container(
child: Container(child: Text("${widget.someInt}"),),
);
}
}
In the above code I passed someInt to NewPage class.
In the first page you should navigate like this:
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => NewPage(someInt: 293,),
));
put above code in the onPressed and pass the data with constructor.

Related

Pass parameters to a route widget correctly

I am new to flutter, and have some difficulties understanding how to correctly pass parameters to a widget that is navigated to.
My goal is, that when the users clicks on a button, I want to start up a wizard controller with a certain enum parameter based on what button the user clicked.
The wizard controller has an app bar but the primary content is a dynamic child wizard flow widget which is chosen based on the enum parameter. The wizard controller (and its children) needs to be stateful because it, among other things, holds information about the current page in the chosen wizard flow and a model which holds data for the whole wizard flow.
As far as I can see there are two options of instantiating the wizard controller with the enum parameter:
Option 1.
//Pass the parameters when the route is pushed
onPressed: () {
Navigator.pushNamed(context, '/wizard', arguments: EFlowType.WizardFlow2);
},
//In the build method, extract the parameter from the navigator, and use it here:
class WizardController extends StatefulWidget {
WizardController({Key? key}) : super(key: key);
#override
State<WizardController> createState() => _WizardControllerState();
}
class _WizardControllerState extends State<WizardController> {
StatefulWidget? dynamicWidget;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
final flowType = ModalRoute.of(context)!.settings.arguments as EFlowType;
switch (flowType) {
case EFlowType.WizardFlow1:
//Prepare models, set dynamicWidget and do alot of work
break;
case EFlowType.WizardFlow2:
//Prepare models, set dynamicWidget and do alot of work
break;
}
return Scaffold(
appBar: AppBar(
title: Text('Wizard controller'),
),
body: dynamicWidget
);
}
....
The problem is here that I would like to access the flowType parameter in the initState (or in the WizardController class constructor), so I dont need to do all the initialization work every time the widget is being rebuild/UI is updated.
If I try to access the flowtype in the initstate I get this error which I cannot come around: FlutterError (dependOnInheritedWidgetOfExactType<_ModalScopeStatus>() or dependOnInheritedElement() was called before _WizardControllerState.initState() completed.
It is not possible to access the context in the WizardController class, so that is not an option.
Option 2.
In the MaterialApp method I can declare an extra onGenerateRoute setting, for these routes in my app that has parameters:
class WizardController extends StatefulWidget {
EFlowType flowType = EFlowType.MeterChange;
WizardController({Key? key, required this.flowType}) : super(key: key);
#override
State<WizardController> createState() => _WizardControllerState();
}
onGenerateRoute: (RouteSettings settings) {
if (settings.name == '/wizard') {
return MaterialPageRoute(builder: (_) => WizardController(flowType: settings.arguments as EFlowType));
}
This makes the flowType available in the initState. But why on earth would I declare context and logic-specific stuff where I am defining my routes? Is this a preferred way of defining widget parameters?
So how would you normally go around this quite normal problem?

How to acces parameter value from constructor in flutter?

I'm having trouble with accessing the value of a parameter from a constructor in my code. I access to this page from another one where I get the value of the parameter:
final route = MaterialPageRoute(
builder: (context) => AnadirJugadores(idPagina: respuesta['id'],));
Navigator.push(context, route);
This is the code of AnadirJugadores:
class AnadirJugadores extends StatefulWidget {
final String idPagina;
AnadirJugadores({required this.idPagina });
String cogerID() {
return this.idPagina;
}
#override
State<AnadirJugadores> createState() => _AnadirJugadoresState();
}
class _AnadirJugadoresState extends State<AnadirJugadores> {
#override
Widget build(BuildContext context) {
.... more code
ElevatedButton(
child: Text(idPartida), // this is the line of the error
onPressed: () {
final data = ClipboardData(text: '25342756374');
Clipboard.setData(data);
},
),
I'm trying to access the value of idPagina. How could I do that?
Thanks in advance.
When using stateful widgets you need to use widget to access the parameters.
child: Text(widget.idPartida),
In StatefulWidget your constructor exists in upper class (it's not in State class), so to access data in this constructor in your state class you should do this:
ElevatedButton(child: Text(widget.idPartida), ...),

how to navigate data between two screens in flutter?

I have homeScreen, which every another screen returns to it.
and one of the screens have parameters from TextField, which I need in the homeScreen, how I can navigate these parameters to the home?
NOTE: when I use constructor, the other screens show an error in the line that navigate to Home because there is no parameters.
You can either use an optional parameter in your constructor:
Homepage({String textfield});
and use it on your Homepage (don't forget that this value is nullable)
Or you need to use some kind of state management with ValueNotifiers
You can pass data using parameters
class XYZ extends StatelessWidget {
final TextEditingController textController = TextEditingController();
void navigationFunction() {
//send the data from XYZ to HomePage
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(textValue: textController.text)),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({this.textValue});
final String textValue; //use this textValue in HomePage
#override
Widget build(BuildContext context) {
return Scaffold();
}
}

Data passed to Stateful Flutter Widget using Navigator.pushNamed() is null

Using Flutter, I am trying to pass data via the constructor to a new screen.
However, this is somewhat of a special case because the screen is a Stateful widget and I am using the Navigation Routes method of navigation.
The data also happens to be of type int, if that matters.
The named route navigation is set up like so:
void main() => runApp(Main());
class Main extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: PreLoadScreen.id,
//initialRoute: TemporaryScreen.id,
routes: {
TemporaryScreen.id: (context) => TemporaryScreen(),
InfoScreen.id: (context) => InfoScreen(),
PreLoadScreen.id: (context) => PreLoadScreen(),
StatsScreen.id: (context) => StatsScreen(),
RideScreen.id: (context) => RideScreen(),
AudioScreen.id: (context) => AudioScreen(),
},
);
}
}
The screen that I'm passing the data to has the following constructor code:
class StatsScreen extends StatefulWidget {
static const String id = 'stats_screen';
int tableID; // current shift table ID being passed in from super
// Constructor required for having data passed in
StatsScreen({Key key, #required this.tableID}) : super(key: key);
#override
_StatsScreenState createState() {
print('statsscreen DEBUG: $tableID'); // <-- this shows the data passed was NULL! :(
return _StatsScreenState();
}
}
The screen that I'm passing the data FROM contains the following code:
void _checkShiftStatus() async {
bool userClockedIn = await ShiftManager().isUserClockedIn();
int tableName = await ShiftManager().getActiveRideTableName();
print('preload DEBUG: tablename: $tableName'); // <-- this verifies the data is NOT null here.
if (userClockedIn) {
Navigator.pushNamed(context, StatsScreen.id,
arguments: {'tableID': tableName}); // <--- something is wrong here, presumably
} else {
shouldDisplayStartShift = !userClockedIn;
showProgressSpinner = false;
}
}
I've tried changing the suspect line to:
Navigator.pushNamed(context, StatsScreen.id,
arguments: tableName);
and...
Navigator.pushNamed(context, StatsScreen.id,
arguments: {tableName});
But get the same result in the target screen (data passed is null). It's sort of like baseball... the batter is the initial screen... and the catcher is the screen we're navigating to. The ball is the data. Except in my case, the batter seems to be Sammy Sosa and the ball is out of the park someplace... which is great for the Cubs but not for me.
I've also tried googling, docs, stackoverflow (even this specific answer... but I can't seem to extract the pertinent meaning from it), and Bacardi... and I'm getting very annoyed. Please someone point out my syntax error and what line it's on. Thank you!
You have to access data using ModalRoute.
class Delete2 extends StatefulWidget {
Delete2({Key key}) : super(key: key);
#override
_Delete2State createState() => _Delete2State();
}
class _Delete2State extends State<Delete2> {
#override
Widget build(BuildContext context) {
final int args = ModalRoute.of(context).settings.arguments;
return Container(
child: Text(args.toString()),
);
}
}
(Full Documentation)

How do I navigate to a page that has a constructor parameter?

I have a flutter stateful page. Here it is:
class TestPage extends StatefulWidget {
static const String id = 'TestPage';
final String testString;
TestPage(this.testString);
#override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(child: Text('Hello ${widget.testString}'))
);
}
}
The page has a constructor that takes in a string as a default value.
final String testString;
From another page, I make a call to that page. I want to open it and give it or pass to it a String value:
Navigator.pushNamed(context, TestPage(myString));
However, it is telling me:
that the argument type 'TestPage' cannot be assigned to the parameter type String.
What am I doing wrong? Is this not the correct way to instantiate this class and make it appear?
Thank you
Try with this,
Navigator.push( context, MaterialPageRoute( builder: (context) => TestPage(testString: 'Hello',), ));