Reputation: 133
I have made a button in a separate class and was wondering is there a way to navigate to different screens using the same button class I made? The plan is to navigate to different pages by using the onPress() function.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:senior_design/View/Helm.dart';
class Button extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return SizedBox(
width: 100,
height: 100,
child:
RaisedButton(
//alignment: Alignment(100.0, 100.0),
child: Row(
children: <Widget>[
Text("Button"),
]
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Helm()),
);
}
),
);
}
}
Upvotes: 0
Views: 3106
Reputation: 1521
Good afternoon,
I believe that if you can pass a method as a parameter for you to be able to navigate on different screens.
// Creating a custom buttom with a method passed by parameter
class Button extends StatelessWidget {
final VoidCallback onPress;
final double width;
final double height;
Button({this.onPress, this.width, this.height});
@override
Widget build(BuildContext context) {
return SizedBox(
width: width,
height: height,
child: RaisedButton(
color: Colors.pink,
textColor: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Button"),
],),
onPressed: onPress,
),
);
}
}
I did an example on https://dartpad.dev/42c49f8cd0c8dbd834525eb41630d599 for you.
I hope it helps you. hugs.
Upvotes: 2
Reputation: 3361
You can include the function you want to be executed, or the page you want to show, as a variable that you set for your custom button widget:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:senior_design/View/Helm.dart';
class Button extends StatelessWidget {
// include this argument you pass in when the button is constructed
final Widget pageToShow;
Button({this.pageToShow}) : assert(pageToShow != null);
@override
Widget build(BuildContext context) {
// TODO: implement build
return SizedBox(
width: 100,
height: 100,
child: RaisedButton(
//alignment: Alignment(100.0, 100.0),
child: Row(children: <Widget>[
Text("Button"),
]),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => pageToShow,)
);
}),
);
}
}
Upvotes: 2