我正在尝试使用参数 VoidCallback 调用一个小部件,但是当我想调用该小部件时,按下时出现错误: () { }
profile_menu.dart
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
class ProfileMenu extends StatelessWidget {
const ProfileMenu({
super.key,
required this.text,
required this.icon,
this.press,
});
final String text, icon;
final VoidCallback? press;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: TextButton(
onPressed: press,
child: Row(
children: [
SvgPicture.asset(
icon,
width: 22,
),
const SizedBox(width: 20),
Expanded(child: Text(text)),
const Icon(Icons.arrow_forward_ios),
],
),
),
);
}
}
profile_screen.dart
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Profile"),
centerTitle: true,
),
body: const SingleChildScrollView(
padding: EdgeInsets.symmetric(vertical: 20),
child: Column(
children: [
ProfileMenu(
text: "Profile",
icon: "assets/icons/Profile Icon.svg",
press: () {
print('a');
}
),
SizedBox(height: 16),
ProfileMenu(
text: "Account",
icon: "assets/icons/Account Icon.svg",
press: () {
print("b");
}
),
],
),
),
);
}
调用小部件时如何设置按下参数?
删除
const
之前的 SingleChildScrollView
。您传递给 ProfileMenu.press
的回调不是常量,因此 ProfileMenu
不能是常量。因此,SingleChildScrollView
(其父级)也不能保持不变。