Flutter调用showModalBottomSheet报错:Invalid constant value及Invalid function
问题分析与修复方案
错误原因
- Invalid function 错误:
onPressed回调里错误地把showModalBottomSheet函数调用的结果赋值给自身,这是语法错误——函数调用不需要赋值操作。 - Invalid constant value 错误:
FloatingActionButton未声明为const,但它的child属性使用了const Icon,常量修饰符不匹配导致冲突。
修复后的代码
import 'package:flutter/material.dart'; import 'package:todoey/screen/tasks_list.dart'; class TasksScreen extends StatelessWidget { Widget buildBottomSheet(BuildContext context) { return Container(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.lightBlueAccent, floatingActionButton: FloatingActionButton( backgroundColor: Colors.lightBlueAccent, child: Icon(Icons.add), // 移除const修饰符 onPressed: () { // 直接调用showModalBottomSheet,无需赋值 showModalBottomSheet( context: context, builder: buildBottomSheet, ); }, ), body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: const EdgeInsets.only( top: 60.0, left: 30, right: 30, bottom: 30.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const <Widget>[ CircleAvatar( child: Icon( Icons.list, size: 30, color: Colors.lightBlueAccent, ), backgroundColor: Colors.white, radius: 30, ), SizedBox(height: 10), Text( 'Todoey', style: TextStyle( color: Colors.white, fontSize: 50, fontWeight: FontWeight.w700, ), ), Text( '12 task', style: TextStyle( color: Colors.white, ), ), ], ), ), Expanded( child: Container( padding: const EdgeInsets.symmetric(horizontal: 20), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(30.0), topRight: Radius.circular(30)), color: Colors.white, ), child: const TasksList(), ), ), ], ), ); } }
额外提示
- 修正了原代码中
buildButtomSheet的拼写错误(改为buildBottomSheet),属于代码规范优化。 - 如果需要处理底部弹窗关闭后的返回结果,可将
onPressed改为异步回调:onPressed: () async { final result = await showModalBottomSheet( context: context, builder: buildBottomSheet, ); // 在这里处理返回的result },
内容的提问来源于stack exchange,提问作者Jamiekazi
相关产品推荐
相关产品推荐

