You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FlutterFlow自定义函数问题:生成两时间点间时间戳数组

FlutterFlow自定义函数生成时间戳数组报错修复

问题描述

需要实现一个FlutterFlow自定义函数,输入两个时间点from和to,生成包含这两个时间点在内的每分钟时间戳数组(例如从06:00到06:05,返回[06:00, 06:01, ..., 06:05]),但原代码执行报错。

错误原因

原代码存在两个关键问题:

  • 在外部occupiedTime函数内部嵌套定义了同名函数,触发语法错误
  • 外部函数声明返回List<DateTime>但未执行任何返回操作,违反Dart类型规则

修正后的代码

import 'dart:convert';
import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;
import '../../flutter_flow/lat_lng.dart';
import '../../flutter_flow/place.dart';
import '../../flutter_flow/custom_functions.dart';
import '/backend/backend.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '/auth/firebase_auth/auth_util.dart';

List<DateTime> occupiedTime(
  DateTime from,
  DateTime to, [
  Duration duration = const Duration(minutes: 1),
]) {
  /// MODIFY CODE ONLY BELOW THIS LINE
  List<DateTime> timestamps = [];
  // 创建from的副本,避免修改原始传入参数
  DateTime currentTime = DateTime.fromMillisecondsSinceEpoch(from.millisecondsSinceEpoch);
  
  while (currentTime.isBefore(to) || currentTime.isAtSameMomentAs(to)) {
    timestamps.add(currentTime);
    currentTime = currentTime.add(duration);
  }
  
  return timestamps;
  /// MODIFY CODE ONLY ABOVE THIS LINE
}

代码说明

  • 移除嵌套函数定义,直接在主函数内实现核心逻辑
  • 创建currentTime副本操作,避免修改外部传入的原始DateTime对象
  • 循环条件包含isAtSameMomentAs,确保to时间点被包含在结果数组中
  • 保留可选参数duration,默认步长为1分钟,可按需调整为其他时间间隔

使用注意

  • 在FlutterFlow中调用时,需确保传入的from和to为有效DateTime类型,且from时间不晚于to时间
  • 若固定步长为1分钟,可删除可选参数duration,直接在代码中写死Duration(minutes: 1)

内容的提问来源于stack exchange,提问作者Con Other

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:12:19