flutter - Flutter:从子小部件调用父函数
问题描述
您好,我想从子小部件(customappbar)调用一个函数,例如打开抽屉。
有我的代码:
home_page.dart
import 'package:fahrschuleapp/widget/appbar_widget.dart';
import 'package:fahrschuleapp/widget/sidebar_widget.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
drawerEnableOpenDragGesture: false,
body: SafeArea(
child: Center(
child: Column(
children: [
CustomAppBar(
pFunction: CustomAppBarFunction.menu,
pContext: context,
pTitle: 'test',
),
],
),
),
),
drawer: SideBar(),
);
}
}
我试图用参数“pFunction”说应该调用哪个函数,例如_callFunction中的导航器弹出或打开菜单等
appbar_widget.dart
import 'package:flutter/material.dart';
enum CustomAppBarFunction {
menu,
back,
exit,
}
class CustomAppBar extends StatelessWidget {
CustomAppBar({
Key? key,
required this.pTitle,
required this.pContext,
required this.pFunction,
}) : super(key: key);
CustomAppBarFunction pFunction;
String pTitle;
BuildContext pContext;
final List<IconData> _iconList = [
Icons.menu,
Icons.arrow_back,
Icons.close,
];
_callFunction(int index) {
switch (index) {
case 0:
Scaffold.of(pContext).openDrawer();
break;
default:
break;
}
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(
left: 20,
right: 20,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.all(8),
child: IconButton(
onPressed: _callFunction(pFunction.index),
icon: Icon(
_iconList[pFunction.index],
),
),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(15)),
color: Theme.of(context).colorScheme.primary,
),
),
Container(
padding: const EdgeInsets.only(left: 15, right: 15),
child: Text(
pTitle,
style: const TextStyle(
fontFamily: 'Hellix',
fontSize: 20,
),
),
),
const SizedBox(
width: 50.4,
),
],
),
);
}
}
我试图在小部件内部调用,_callFunction
但这不起作用错误输出:
使用不包含 Scaffold 的上下文调用 Scaffold.of()。
我该如何解决?还是有更好的方法来做到这一点?
解决方案
将您的 IconButton 更改为以下代码,
Builder(builder: (context) {
return IconButton(
onPressed:() => _callFunction(pFunction.index, context),
icon: Icon(
_iconList[pFunction.index],
),
) ;
})
并改变你的 _callFunction,
_callFunction(int index, BuildContext mContext) {
switch (index) {
case 0:
Scaffold.of(mContext).openDrawer();
break;
default:
break;
}
}
推荐阅读
- javascript - 为什么打字稿在类型联合上给出类型错误?
- android - 当我尝试将我的颤振应用程序与 firebase 连接时出现错误
- android - 如何在Android中对齐两个视图?
- r - 如何防止 RShiny 应用程序中的配置单元会话超时
- python - 为什么 Keras 损失在第一个 epoch 之后急剧下降?
- javascript - IMG src 标签在 reactJS 组件中无法正常工作
- java - 如何使用 Azure CLI 脚本将 Azure Application Insights 正确连接到应用服务 Spring 应用程序?
- php - 在 Symfony 2.8 中将服务注入控制器?
- docker-compose - Dgraph 总是显示'Connection lost with alpha: 7080' 错误
- javascript - 在 StrictMode 中不推荐对 findDOMNode 进行查询