我现在正在尝试制作一个可以通过两个不同的按钮打开的页面。因此,例如,在我的主页中会有这些按钮,当我按它时,它将打开一个页面。然后,当我按下另一个按钮时,它将像这样打开同一页面:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp (
title: 'Navigation Basics',
debugShowCheckedModeBanner: false,
home: FirstRoute(),
)
);
}
class FirstRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Route'),
),
body: Center(
child: Column (
children: <Widget> [
Hero (
tag: 'open',
child: RaisedButton(
child: Text('Open route'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
),
),
Hero (
tag: 'open',
child: RaisedButton(
child: Text('Open route'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
),
)
]
)
),
);
}
}
class SecondRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold (
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: Hero (
tag: 'open',
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
)
),
);
}
}
但是由于某种原因,这是一个问题。如果按这些按钮,则可以打开页面,但不能返回。我该如何解决?
答案 0 :(得分:1)
确保使用唯一的hero
标签。
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Navigation Basics',
debugShowCheckedModeBanner: false,
home: FirstRoute(),
));
}
class FirstRoute extends StatelessWidget {
final String open1 = 'open';
final String open2 = 'open2';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Route'),
),
body: Center(
child: Column(children: <Widget>[
Hero(
tag: open1,
child: RaisedButton(
child: Text('Open route'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondRoute(
open: open1,
)),
);
},
),
),
Hero(
tag: open2,
child: RaisedButton(
child: Text('Open route'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondRoute(
open: open2,
)),
);
},
),
)
])),
);
}
}
class SecondRoute extends StatelessWidget {
final String open;
SecondRoute({this.open});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Center(
child: Hero(
tag: open,
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
)),
);
}
}