【发布时间】:2020-06-02 02:52:47
【问题描述】:
希望你能帮我解决这个问题!这几天我一直在扯头发,所以任何帮助都将不胜感激。
我想在我当前项目的 sqflite 表中添加一个“日期”列。这是 database_helper.dart 的代码:
import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
class DatabaseHelper {
static final _databaseName = "MyDatabase.db";
static final _databaseVersion = 1;
static final table = 'my_table';
static final columnId = '_id';
static final columnName = 'name';
static final columnAge = 'age';
static final columnColour = 'colour';
static final columnDateTime = 'datetime';
// make this a singleton class
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
// only have a single app-wide reference to the database
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
// lazily instantiate the db the first time it is accessed
_database = await _initDatabase();
return _database;
}
// this opens the database (and creates it if it doesn't exist)
_initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, _databaseName);
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
// SQL code to create the database table
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY,
$columnName TEXT NOT NULL,
$columnAge INTEGER NOT NULL,
$columnColour TEXT NOT NULL,
$columnDateTime TEXT NOT NULL
)
''');
}
// Helper methods
// Inserts a row in the database where each key in the Map is a column name
// and the value is the column value. The return value is the id of the
// inserted row.
Future<int> insert(Map<String, dynamic> row) async {
Database db = await instance.database;
return await db.insert(table, row);
}
// All of the rows are returned as a list of maps, where each map is
// a key-value list of columns.
Future<List<Map<String, dynamic>>> queryAllRows() async {
Database db = await instance.database;
return await db.query(table);
}
// All of the methods (insert, query, update, delete) can also be done using
// raw SQL commands. This method uses a raw query to give the row count.
Future<int> queryRowCount() async {
Database db = await instance.database;
return Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM $table'));
}
// We are assuming here that the id column in the map is set. The other
// column values will be used to update the row.
Future<int> update(Map<String, dynamic> row) async {
Database db = await instance.database;
int id = row[columnId];
return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
}
// Deletes the row specified by the id. The number of affected rows is
// returned. This should be 1 as long as the row exists.
Future<int> delete(int id) async {
Database db = await instance.database;
return await db.delete(table, where: '$columnId = ?', whereArgs: [id]);
}
}
这是 main.dart 的代码:
import 'package:flutter/material.dart';
// change `flutter_database` to whatever your project name is
import 'package:flutter_database/database_helper.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SQFlite Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
// reference to our single class that manages the database
final dbHelper = DatabaseHelper.instance;
// homepage layout
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('sqflite'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text('insert', style: TextStyle(fontSize: 20),),
onPressed: () {_insert();},
),
RaisedButton(
child: Text('query', style: TextStyle(fontSize: 20),),
onPressed: () {_query();},
),
],
),
),
);
}
// Button onPressed methods
void _insert() async {
// row to insert
Map<String, dynamic> row = {
DatabaseHelper.columnName : 'Bob',
DatabaseHelper.columnAge : 23,
DatabaseHelper.columnColour : 'Red',
DatabaseHelper.columnDateTime : DateTime.now().toIso8601String(),
};
final id = await dbHelper.insert(row);
print('inserted row id: $id');
}
void _query() async {
final allRows = await dbHelper.queryAllRows();
print('query all rows:');
allRows.forEach((row) => print(row));
}
}
我们的目标是简单地将今天的日期记录下来——我不需要记录其中的一部分,只需记录日期即可。如果您运行上面的代码,如果您单击“查询”按钮,日期时间会显示在控制台中,但我希望它只存储今天的日期,而不是时间。
我查看了 intl 包的文档,因为我读到这是格式化日期的好方法,但在这种情况下我不知道如何在我的代码中实现它。
任何想法将不胜感激!
非常感谢,
杰森
【问题讨论】:
-
感谢您的回复。不过还在努力解决!你的意思是我应该把它转换成一个整数而不是 toIso8601String()?
-
是的,这是最灵活的格式
-
好的,非常感谢,我会玩一下代码。为您的帮助喝彩!
-
当然,欢迎您-查看DateFormat官方文档