我正在尝试在我的Flutter应用中实现CupertinoActionSheet,但我一直失败。我很确定我拥有所有必要的东西,但是我一直遇到以下错误:
导航器请求的上下文不包含导航器。
我不明白为什么会收到此错误。实施CupertinoActionSheet的正确方法是什么?
代码:
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Container(
color: Colors.black,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Card(
elevation: 20,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 180.0),
child: CupertinoButton(
color: Colors.black,
child: Text(
'Click me',
style: TextStyle(color: Colors.white),
),
onPressed: () {
final act = CupertinoActionSheet(
title: Text('Select Option'),
message:
Text('Which option?'),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text('1'),
onPressed: () {
print('pressed');
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
));
showCupertinoModalPopup(
context: context,
builder: (BuildContext context) => act);
},
),
),
]),
),
),
),
),
),
),
);
}
}
您可以使用StatefulBuilder,请参见下面的完整代码代码段
children: <Widget>[
StatefulBuilder(builder:
(BuildContext context, StateSetter setState) {
return Padding(
padding: const EdgeInsets.only(top: 180.0),
child: CupertinoButton(
完整代码
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Container(
color: Colors.black,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Card(
elevation: 20,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
StatefulBuilder(builder:
(BuildContext context, StateSetter setState) {
return Padding(
padding: const EdgeInsets.only(top: 180.0),
child: CupertinoButton(
color: Colors.black,
child: Text(
'Click me',
style: TextStyle(color: Colors.white),
),
onPressed: () {
final act = CupertinoActionSheet(
title: Text('Select Option'),
message: Text('Which option?'),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text('1'),
onPressed: () {
print('pressed');
},
)
],
cancelButton: CupertinoActionSheetAction(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
));
showCupertinoModalPopup(
context: context,
builder: (BuildContext context) => act);
},
),
);
})
]),
),
),
),
),
),
),
);
}
}