Reputation: 49
i'm kinda new to flutter and i'm trying to get two buttons on my page and make them send the user to different pages on my app. Right now I have this code for my buttons, but to make it work, I just change the last part of the code from SearchPage() to ScanPage() and this seems to be inefficient. Can I somehow pass in the pages as arguements for the button widgets?
// Button for scanPage
Widget _buttonScan(String text, Color splashColor, Color highlightColor,
Color fillColor, Color textColor) {
return RaisedButton(
highlightElevation: 0.0,
splashColor: splashColor,
highlightColor: highlightColor,
elevation: 0.0,
color: fillColor,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0)),
child: Text(
text,
style: TextStyle(
fontWeight: FontWeight.bold, color: textColor, fontSize: 20),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScanPage()),
);
},
);
}
// Button for searchPage
Widget _buttonSearch(String text, Color splashColor, Color highlightColor,
Color fillColor, Color textColor) {
return RaisedButton(
highlightElevation: 0.0,
splashColor: splashColor,
highlightColor: highlightColor,
elevation: 0.0,
color: fillColor,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0)),
child: Text(
text,
style: TextStyle(
fontWeight: FontWeight.bold, color: textColor, fontSize: 20),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SearchPage()),
);
},
);
}
Upvotes: 1
Views: 716
Reputation: 122
You can pass a function as an argument to your widget that will take care of the navigation direction. In your case, either go to scanPage or searchPage, like this:
Widget _buttonScan(String text, Color splashColor, Color highlightColor,
Color fillColor, Color textColor, Widget Function() choosePage) {
return RaisedButton(
highlightElevation: 0.0,
splashColor: splashColor,
highlightColor: highlightColor,
elevation: 0.0,
color: fillColor,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0)),
child: Text(
text,
style: TextStyle(
fontWeight: FontWeight.bold, color: textColor, fontSize: 20),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => choosePage()),
);
},
);
}
And when you call it:
_buttonScan(...,() => ScanPage ()) //To go to ScanPage
_buttonScan(...,() => SearchPage()) //To go to SearchPage
Upvotes: 1
Reputation: 2215
To pass arguments you need to use named routes of the Navigator
like this :
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);
See the official documentation
Upvotes: 0