Dart中如何在Text Widget的字符串中使用函数返回的字符串值
Dart中Text Widget字符串插值调用函数的正确写法
你的问题出在Dart字符串插值的语法上:直接写$getCurrentDate(task.date)时,Dart会将函数本身和参数视为字面量输出,而不会执行函数调用,所以显示的是函数闭包信息。
正确写法
要让函数执行并插入返回值,需要将完整的函数调用用大括号包裹,放在插值表达式中:
Text( 'Due to ${getCurrentDate(task.date)}', style: TextStyle( fontWeight: FontWeight.w200, color: Colors.grey, ), )
优化日期格式化函数
另外你的getCurrentDate函数可以简化,因为传入的date已经是DateTime类型,不需要先转字符串再解析,直接使用即可:
String getCurrentDate(DateTime date) { return "${date.day}.${date.month}.${date.year}"; }
这样修改后,Text Widget就能正常显示Due to 11.2.2023这类格式化后的日期了。
内容的提问来源于stack exchange,提问作者comhendrik
相关产品推荐
相关产品推荐

