Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 将DateTime对象转换为DateTime字符串,以便我可以将数据插入sqflite_Flutter_Dart_Flutter Dependencies - Fatal编程技术网

Flutter 将DateTime对象转换为DateTime字符串,以便我可以将数据插入sqflite

Flutter 将DateTime对象转换为DateTime字符串,以便我可以将数据插入sqflite,flutter,dart,flutter-dependencies,Flutter,Dart,Flutter Dependencies,我正在构建一个待办应用程序,用户必须在特定的日期和时间安排要执行的任务 根据我在网上看到的教程,我已经能够构建我的日期和时间选择器,但是现在我正试图使用flatter SQflite将所选的日期和时间保存到SQL,我了解到,目前我们无法将DateTime对象直接保存到数据库,除非它被转换为String或Int 现在我在转换它时遇到问题。。。也许是因为我不知道它是怎么做到的,我一直都会出错 无法将“String”类型的值分配给类型为的变量 “日期时间”。尝试更改变量的类型,或强制转换 右键键入“D

我正在构建一个待办应用程序,用户必须在特定的日期和时间安排要执行的任务

根据我在网上看到的教程,我已经能够构建我的日期和时间选择器,但是现在我正试图使用flatter SQflite将所选的日期和时间保存到SQL,我了解到,目前我们无法将DateTime对象直接保存到数据库,除非它被转换为String或Int

现在我在转换它时遇到问题。。。也许是因为我不知道它是怎么做到的,我一直都会出错

无法将“String”类型的值分配给类型为的变量 “日期时间”。尝试更改变量的类型,或强制转换 右键键入“DateTime”

我能够使用Intl软件包格式化所选的日期和时间。。。检查图像以查看其格式

下面是我的代码。。。selectedDayAndTime是我要更改为字符串的DateTime对象

import './model.dart';

class TodoItem extends Model {
  static String table = 'todo_items';

  int id;
  String title;
  String description;
  String date;
  bool complete;

  TodoItem({this.id, this.title, this.description, this.date, this.complete});

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = {
      'title': title,
      'description': description,
      'date': date,
      'complete': complete,
    };

    if (id != null) {
      map['id'] = id;
    }
    return map;
  }

  static TodoItem fromMap(Map<String, dynamic> map) {
    return TodoItem(
        id: map['id'],
        title: map['title'],
        description: map['description'],
        date: map['date'],
        complete: map['complete'] == 1);
  }
}
导入“/model.dart”; 类TodoItem扩展了模型{ 静态字符串表='待办事项'; int-id; 字符串标题; 字符串描述; 字符串日期; 布尔完成; TodoItem({this.id,this.title,this.description,this.date,this.complete}); 映射toMap(){ 地图={ “标题”:标题, “描述”:描述, “日期”:日期, “完成”:完成, }; 如果(id!=null){ map['id']=id; } 返回图; } 静态TodoItem fromMap(映射映射){ 返回DoItem( id:map['id'], 标题:地图['title'], 描述:地图['description'], 日期:映射['date'], 完成:映射['complete']==1); } } 然后我的数据库代码

import 'dart:async';
import '../models/model.dart';
import 'package:sqflite/sqflite.dart';

abstract class DB {
  static Database _db;

  static int get _version => 3;

  static Future<void> init() async {
    if (_db != null) {
      return;
    }

    try {
      String _path = await getDatabasesPath() + 'example';
      _db = await openDatabase(_path, version: _version, onCreate: onCreate);
    } catch (ex) {
      print(ex);
    }
  }

  static void onCreate(Database db, int version) async => await db.execute(
      'CREATE TABLE todo_items (id INTEGER PRIMARY KEY NOT NULL, title STRING NOT NULL, description STRING, date TEXT, complete BOOLEAN)');


  static Future<int> insert(String table, Model model) async =>
      await _db.insert(table, model.toMap());
}
导入'dart:async';
导入“../models/model.dart”;
导入“包:sqflite/sqflite.dart”;
抽象类数据库{
静态数据库;
静态int get_version=>3;
静态Future init()异步{
如果(_db!=null){
返回;
}
试一试{
字符串_path=await getDatabasesPath()+'示例';
_db=等待openDatabase(_路径,版本:_版本,onCreate:onCreate);
}捕获(ex){
印刷品(ex);
}
}
静态void onCreate(数据库db,int版本)async=>wait db.execute(
'创建表todo_项(id整数主键不为NULL、标题字符串不为NULL、说明字符串、日期文本、完整布尔值)';
静态未来插入(字符串表、模型)异步=>
wait _db.insert(表,model.toMap());
}
然后在我的Main.dart文件上

class _MyHomePageState extends State<MyHomePage> {
  // String _task;
  String titleInput;
  String descriptionInput;
  DateTime selectedDateAndTime;

  List<TodoItem> _tasks = [];
Future _selectDayAndTimeL(BuildContext context) async {
    DateTime _selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget child) => child);

    TimeOfDay _selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (_selectedDay != null && _selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        _selectedDay.year,
        _selectedDay.month,
        _selectedDay.day,
        _selectedTime.hour,
        _selectedTime.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

// This is the Save function
void _save() async {
    Navigator.of(context).pop();
    TodoItem item = TodoItem(
        title: titleInput,
        description: descriptionInput,
        date: selectedDateAndTime,
        complete: false);

    await DB.insert(TodoItem.table, item);
    setState(() {
      titleInput = '';
      descriptionInput = '';
      selectedDateAndTime = ''; // I tried this but kept getting that same error
    });
    refresh();
  }
class\u MyHomePageState扩展状态{
//字符串任务;
字符串标题输入;
字符串描述输入;
日期时间选择日期和时间;
列表_任务=[];
Future\u选择day和timel(BuildContext上下文)异步{
DateTime\u selectedDay=等待显示日期选择器(
上下文:上下文,
initialDate:DateTime.now(),
firstDate:DateTime(2021年),
最后日期:日期时间(2030年),
生成器:(BuildContext上下文,小部件子项)=>child);
TimeOfDay\u selectedTime=等待显示时间选择器(
上下文:上下文,
initialTime:TimeOfDay.now(),
);
如果(_selectedDay!=null&&u selectedTime!=null){
//小支票
}
设置状态(){
selectedDateAndTime=日期时间(
_选择日期。年份,
_选择日期、月份,
_选择的日期,
_选择time.hour,
_选择time.minute,
);
//_selectedDate=_selectedDay;
});
//印刷品(“…”);
}
//这是保存功能
void\u save()异步{
Navigator.of(context.pop();
TodoItem项目=TodoItem(
标题:标题输入,
描述:描述输入,
日期:选择日期和时间,
完整:假);
等待数据库插入(TodoItem.table,item);
设置状态(){
标题输入=“”;
descriptionInput='';
selectedDateAndTime='';//我尝试了这个方法,但始终得到相同的错误
});
刷新();
}

您可以通过两种方法轻松转换和还原日期时间,以便将其保存到数据库:

  • 转换为格式化字符串:
  • void main(){
    var dt=new DateTime.now();
    var formatter=new DateFormat('yyyy-MM-dd HH:MM:ss');
    String formatted=formatter.format(dt);//将其保存到数据库
    打印(格式化);//输出:2021-05-11 08:52:45
    print(formatter.parse(formatted));//转换回DateTime对象
    }
    
  • 转换为UNIX时间:
  • void main(){
    final dt=DateTime.now();
    final dtInEpoch=dt.millissecondssinceepoch;//将其保存到DB
    打印(dtInEpoch);//输出:1620697965915
    打印(DateTime.froms毫秒nceepoch(dtInEpoch));//转换回DateTime对象
    }
    
    我试图选择要在Listtile字幕中显示的日期和时间,但它没有显示…只是显示为空白…这是我尝试调用它的代码
    字幕:Text(格式化!=null?格式化:“默认日期”),
    还尝试调用日期,以查看我是否调用了错误的函数,但仍然给出了相同的问题
    副标题:Text(item.Date!=null?item.Date:“default Date And Time',),'
    这就是我如何添加您给出的修复方法
    字符串格式;DateTime selectedDateAndTime;
    void main(){var dt=new DateTime.now();var formatter=new DateFormat('yyyy-MM-dd HH:MM:ss');String formatted=formatter.format(dt);//将此保存到DB print(格式化);//输出:2021-05-11 08:52:45 print(formatter.parse(格式化));//转换回DateTime对象