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

Flutter中moment_dart库使用报错求助:三个方法未定义

Flutter中moment_dart库日期处理报错修复

我正在开发一款演示moment_dart库在Flutter中进行日期时间处理与格式化的应用,编写的代码如下:

import 'package:flutter/material.dart';
import 'package:moment_dart/moment_dart.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Moment Demo',
      home: MomentDemo(),
    );
  }
}

class MomentDemo extends StatefulWidget {
  @override
  _MomentDemoState createState() => _MomentDemoState();
}

class _MomentDemoState extends State<MomentDemo> {
  Moment _startDate = Moment.utc([2023, 1, 1]);
  Moment _endDate = Moment.utc([2023, 2, 28]);

  List<String> _dates = [    
    '2023-01-01',    
    '2023-01-08',    
    '2023-01-15',    
    '2023-01-22',    
    '2023-01-29',    
    '2023-02-05',    
    '2023-02-12',    
    '2023-02-19',    
    '2023-02-26',    
    '2023-03-05',  
  ];
  List<String> _filteredDates = [];

  void _filterDates() {
    _filteredDates = _dates.where((date) {
      Moment moment = Moment.parse(date);
      return moment.isAfter(_startDate) && moment.isBefore(_endDate);
    }).toList();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Moment Demo'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: _startDate.toDateTime(),
                      firstDate: DateTime.utc(2023),
                      lastDate: _endDate.toDateTime(),
                    ).then((value) {
                      if (value != null) {
                        _startDate = Moment.fromDateTime(value.toUtc());
                        _filterDates();
                      }
                    });
                  },
                  child: Text('Başlangıç Tarihi Seç'),
                ),
                ElevatedButton(
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: _endDate.toDateTime(),
                      firstDate: DateTime.utc(2023),
                      lastDate: DateTime.utc(2023, 12, 31),
                    ).then((value) {
                      if (value != null) {
                        _endDate = Moment.fromDateTime(value.toUtc());
                        _filterDates();
                      }
                    });
                  },
                  child: Text('Bitiş Tarihi Seç'),
                ),
              ],
            ),
            SizedBox(height: 16.0),
            Text(
              'Başlangıç Tarihi: ${_startDate.format("dd/MM/yyyy")}',
              style: TextStyle(fontSize: 16.0),
            ),
            SizedBox(height: 8.0),
            Text(
              'Bitiş Tarihi: ${_endDate.format("dd/MM/yyyy")}',
              style: TextStyle(fontSize: 16.0),
            ),
            SizedBox(height: 16.0),
            Expanded(
              child: ListView.builder(
                itemCount: _filteredDates.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(_filteredDates[index]),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

运行代码时出现以下错误:

  • 类型'Moment'未定义方法'utc'
  • 类型'Moment'未定义方法'toDateTime'
  • 类型'Moment'未定义方法'fromDateTime'

错误原因与修复方案

这些错误源于使用了moment_dart库不存在的API,以下是对应修复点和完整修正代码:

  1. 创建UTC时间的Moment实例:
    moment_dart没有接受数组参数的utc静态方法,可通过传入DateTime.utc()实例来创建UTC时间的Moment对象。

  2. Moment转DateTime:
    Moment实例没有toDateTime()方法,直接访问dateTime属性即可获取对应的DateTime对象。

  3. 从DateTime创建Moment:
    不需要fromDateTime()静态方法,直接使用Moment构造函数传入DateTime实例即可。


修正后的完整代码

import 'package:flutter/material.dart';
import 'package:moment_dart/moment_dart.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Moment Demo',
      home: MomentDemo(),
    );
  }
}

class MomentDemo extends StatefulWidget {
  @override
  _MomentDemoState createState() => _MomentDemoState();
}

class _MomentDemoState extends State<MomentDemo> {
  // 修复:通过DateTime.utc创建Moment实例
  Moment _startDate = Moment(DateTime.utc(2023, 1, 1));
  Moment _endDate = Moment(DateTime.utc(2023, 2, 28));

  List<String> _dates = [
    '2023-01-01',
    '2023-01-08',
    '2023-01-15',
    '2023-01-22',
    '2023-01-29',
    '2023-02-05',
    '2023-02-12',
    '2023-02-19',
    '2023-02-26',
    '2023-03-05',
  ];
  List<String> _filteredDates = [];

  void _filterDates() {
    _filteredDates = _dates.where((date) {
      Moment moment = Moment.parse(date);
      return moment.isAfter(_startDate) && moment.isBefore(_endDate);
    }).toList();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Moment Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      // 修复:访问dateTime属性获取DateTime
                      initialDate: _startDate.dateTime,
                      firstDate: DateTime.utc(2023),
                      lastDate: _endDate.dateTime,
                    ).then((value) {
                      if (value != null) {
                        // 修复:直接用Moment构造函数传入DateTime
                        _startDate = Moment(value.toUtc());
                        _filterDates();
                      }
                    });
                  },
                  child: const Text('选择开始日期'),
                ),
                ElevatedButton(
                  onPressed: () {
                    showDatePicker(
                      context: context,
                      initialDate: _endDate.dateTime,
                      firstDate: DateTime.utc(2023),
                      lastDate: DateTime.utc(2023, 12, 31),
                    ).then((value) {
                      if (value != null) {
                        _endDate = Moment(value.toUtc());
                        _filterDates();
                      }
                    });
                  },
                  child: const Text('选择结束日期'),
                ),
              ],
            ),
            const SizedBox(height: 16.0),
            Text(
              '开始日期: ${_startDate.format("dd/MM/yyyy")}',
              style: const TextStyle(fontSize: 16.0),
            ),
            const SizedBox(height: 8.0),
            Text(
              '结束日期: ${_endDate.format("dd/MM/yyyy")}',
              style: const TextStyle(fontSize: 16.0),
            ),
            const SizedBox(height: 16.0),
            Expanded(
              child: ListView.builder(
                itemCount: _filteredDates.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(_filteredDates[index]),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:25:42