In CupertinoNavigationBar how do i show a button besides back button in leading?
7,721
Solution 1
Here is a very simple snippet of code. I hope it helps you:
class DemoView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: GestureDetector(
onTap: () {
debugPrint('Back button tapped');
},
child: Row(
children: <Widget>[
Icon(CupertinoIcons.left_chevron),
Text(
'Back',
style: TextStyle(
color: CupertinoColors.activeBlue,
),
),
],
),
),
middle: Text('Demo'),
trailing: GestureDetector(
onTap: () {
debugPrint('add icon tapped');
},
child: Icon(
CupertinoIcons.add,
color: CupertinoColors.black,
),
),
),
child: Center(
child: Text(
'Content',
style: TextStyle(fontSize: 36.0),
),
),
);
}
}
Solution 2
Which is the correct way to add manually back button?
I use code like this:
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text(widget.title),
leading: CupertinoNavigationBarBackButton(
onPressed: () => Navigator.of(context).pop(),
),
child: _myAppBody() // return widget
),
);
}
Comments
-
hgl over 1 year
I tried something like this:
@override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: Text(widget.title), ), child: Center( child: Container( child: CupertinoButton.filled( child: const Text('Push screen'), onPressed: () { CupertinoNavigationBar navBar = CupertinoNavigationBar( leading: Row(children: <Widget>[ const CupertinoNavigationBarBackButton(), CupertinoButton( child: const Text('Button 2'), padding: EdgeInsets.zero, onPressed: () {}, ), ]), ); Navigator.push(context, CupertinoPageRoute<CupertinoPageScaffold>( builder: (_) => CupertinoPageScaffold( navigationBar: navBar, child: Center(child: const Text('Content')), ) )); }, ), ), ), ); }
And when tapping the button, it fails with
I/flutter (30855): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter (30855): The following NoSuchMethodError was thrown building CupertinoNavigationBarBackButton(dirty): I/flutter (30855): The getter 'canPop' was called on null. I/flutter (30855): Receiver: null I/flutter (30855): Tried calling: canPop
The reason is that this code in
CupertinoNavigationBarBackButton
returnsnull
final ModalRoute<dynamic> currentRoute = ModalRoute.of(context);
I wonder why that's the case? Is it because when I push the button,
context
still hasn't gotten the route yet?What's the correct way to manually add a back button?
Thanks in advance.
-
Emre Akcan almost 4 yearsThere is a mistake at debugPrint('add icon tapped')); you have to remove one parenthesis at the end