当前位置: 首页 > news >正文

无涯教程-Flutter - 数据库

SQLite" class="css-1occaib">SQLite数据库是基于事实和标准SQL的嵌入式数据库引擎,它是小型且经过时间考验的数据库引擎,sqflite软件包提供了许多函数,可以有效地与SQLite数据库一起使用,它提供了操作SQLite数据库引擎的标准方法。

  • 在Android Studio中创建一个新的Flutter应用程序product_sqlite_app。

  • 用无涯教程的 product_rest_app 代码替换默认的启动代码(main.dart)。

  • 将assets文件夹从 product_nav_app 复制到 product_rest_app 并在* pubspec.yaml`文件内添加assets。

flutter: assets: - assets/appimages/floppy.png - assets/appimages/iphone.png - assets/appimages/laptop.png - assets/appimages/pendrive.png - assets/appimages/pixel.png - assets/appimages/tablet.png
  • 在pubspec.yaml文件中配置sqflite软件包,如下所示-

dependencies: sqflite: any
  • 在pubspec.yaml文件中配置path_provider软件包,如下所示-

dependencies: path_provider: any
  • 此处,path_provider软件包用于获取系统的临时文件夹路径和应用程序的路径,使用 sqflite 的最新版本号代替任何。

  • Android Studio会提醒pubspec.yaml已更新。

Updated
  • 单击"Get dependencies"选项。 Android studio将从互联网上获取该软件包,并为应用程序正确配置它。

  • 在数据库中,无涯教程需要主键,id作为附加字段以及产品属性(如名称,价格等),因此,请在Product类中添加id属性。另外,添加新方法toMap将产品对象转换为Map对象。 fromMap和toMap用于对Product对象进行序列化和反序列化,并用于数据库操作方法中。

class Product { final int id; final String name; final String description; final int price; final String image; static final columns = ["id", "name", "description", "price", "image"]; Product(this.id, this.name, this.description, this.price, this.image); factory Product.fromMap(Map<String, dynamic> data) {return Product( data[id], data[name], data[description], data[price], data[image], ); } Map<String, dynamic> toMap() => {"id": id, "name": name, "description": description, "price": price, "image": image }; 
}
  • 在lib文件夹中创建一个新文件Database.dart,以编写SQLite的相关函数。

  • 在Database.dart中导入必要的import语句。

import dart:async; 
import dart:io; 
import package:path/path.dart; 
import package:path_provider/path_provider.dart; 
import package:sqflite/sqflite.dart; 
import Product.dart;
  • 请注意以下几点-

    • async                    -  用于编写异步方法。

    • io                           -  用于访问文件和目录。

    • path                      -  用于访问与文件路径相关的dart核心实用程序函数。

    • path_provider    -  用于获取临时路径和应用程序路径。

    • sqflite                   -  用于操作SQLite的数据库。

  • 创建一个新的类SQLite的DbProvider

  •     - 声明一个基于单例的静态SQLite的DbProvider对象,如下所示:

class SQLiteDbProvider { SQLiteDbProvider._(); static final SQLiteDbProvider db=SQLiteDbProvider._(); static Database _database; 
} 
  •     - 可以通过静态db变量访问SQLite的DBProvoider对象及其方法。

SQLiteDBProvoider.db.<emthod> 
  •     - 创建一个方法来获取类型为Future <Database>的数据库,创建产品表并在数据库本身创建期间加载初始数据。

Future<Database> get database async { if (_database != null) return _database; _database = await initDB(); return _database; 
}
initDB() async { Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, "ProductDB.db"); return await openDatabase(path, version: 1,onOpen: (db) {}, onCreate: (Database db, int version) async {await db.execute("CREATE TABLE Product (""id INTEGER PRIMARY KEY,""name TEXT,""description TEXT,""price INTEGER," "image TEXT" ")"); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [1, "iPhone", "iPhone is the stylist phone ever", 1000, "iphone.png"]); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [2, "Pixel", "Pixel is the most feature phone ever", 800, "pixel.png"]); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [3, "Laptop", "Laptop is most productive development tool", 2000, "laptop.png"]\); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [4, "Tablet", "Laptop is most productive development tool", 1500, "tablet.png"]);await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [5, "Pendrive", "Pendrive is useful storage medium", 100, "pendrive.png"]);await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [6, "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy.png"]); }); 
}
  • 在这里,无涯教程使用了以下方法-

    •     -  getApplicationDocumentsDirectory -  返回应用程序目录路径

    •     -  join                        - 用于创建系统特定的路径,无涯教程已经使用它来创建数据库路径。

    •     -  openDatabase     - 用于打开SQLite的数据库。

    •     -  onOpen                - 用于在打开数据库时编写代码

    •     -  onCreate              - 用于在首次创建数据库时编写代码

    •     -  db.execute           - 用于执行SQL查询。它接受一个查询。如果查询具有占位符(?),则它将接受值作为第二个参数中的列表。

  • 编写getAllProducts来获取数据库中的所有产品-

Future<List<Product>> getAllProducts() async { final db = await database; List<Map> results = await db.query("Product", columns: Product.columns, orderBy: "id ASC"); List<Product> products = new List(); results.forEach((result) { Product product = Product.fromMap(result); products.add(product); }); return products; 
}
  • 编写getProductById来获取特定于 id的产品

Future<Product> getProductById(int id) async {final db = await database; var result = await db.query("Product", where: "id=", whereArgs: [id]); return result.isNotEmpty ? Product.fromMap(result.first) : Null; 
}
  • 在这里,无涯教程使用了where和whereArgs来应用过滤器。

  • 创建三种方法-插入,更新和删除方法,以从数据库中插入,更新和删除产品。

insert(Product product) async { final db = await database; var maxIdResult = await db.rawQuery("SELECT MAX(id)+1 as last_inserted_id FROM Product");var id = maxIdResult.first["last_inserted_id"]; var result = await db.rawInsert("INSERT Into Product (id, name, description, price, image)" " VALUES (?, ?, ?, ?, ?)", [id, product.name, product.description, product.price, product.image] ); return result; 
}
update(Product product) async { final db = await database; var result = await db.update("Product", product.toMap(), where: "id=?", whereArgs: [product.id]); return result; 
} 
delete(int id) async { final db = await database; db.delete("Product", where: "id=?", whereArgs: [id]); 
}
  • Database.dart的最终代码如下-

import dart:async; 
import dart:io; 
import package:path/path.dart; 
import package:path_provider/path_provider.dart; 
import package:sqflite/sqflite.dart; 
import Product.dart; class SQLiteDbProvider {SQLiteDbProvider._(); static final SQLiteDbProvider db = SQLiteDbProvider._(); static Database _database; Future<Database> get database async {if (_database != null) return _database; _database = await initDB(); return _database; } initDB() async {Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, "ProductDB.db"); return await openDatabase(path, version: 1, onOpen: (db) {}, onCreate: (Database db, int version) async {await db.execute("CREATE TABLE Product (" "id INTEGER PRIMARY KEY," "name TEXT," "description TEXT," "price INTEGER," "image TEXT"")"); await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [1, "iPhone", "iPhone is the stylist phone ever", 1000, "iphone.png"]); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [2, "Pixel", "Pixel is the most feature phone ever", 800, "pixel.png"]);await db.execute("INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [3, "Laptop", "Laptop is most productive development tool", 2000, "laptop.png"]); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [4, "Tablet", "Laptop is most productive development tool", 1500, "tablet.png"]); await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [5, "Pendrive", "Pendrive is useful storage medium", 100, "pendrive.png"]);await db.execute( "INSERT INTO Product (id, name, description, price, image) values (?, ?, ?, ?, ?)", [6, "Floppy Drive", "Floppy drive is useful rescue storage medium", 20, "floppy.png"]); }); }Future<List<Product>> getAllProducts() async {final db = await database; List<Map> results = await db.query("Product", columns: Product.columns, orderBy: "id ASC"); List<Product> products = new List();   results.forEach((result) {Product product = Product.fromMap(result); products.add(product); }); return products; } Future<Product> getProductById(int id) async {final db = await database; var result = await db.query("Product", where: "id=", whereArgs: [id]); return result.isNotEmpty ? Product.fromMap(result.first) : Null; } insert(Product product) async { final db = await database; var maxIdResult = await db.rawQuery("SELECT MAX(id)+1 as last_inserted_id FROM Product"); var id = maxIdResult.first["last_inserted_id"]; var result = await db.rawInsert("INSERT Into Product (id, name, description, price, image)" " VALUES (?, ?, ?, ?, ?)", [id, product.name, product.description, product.price, product.image] ); return result; } update(Product product) async { final db = await database; var result = await db.update("Product", product.toMap(), where: "id=?", whereArgs: [product.id]); return result; } delete(int id) async { final db = await database; db.delete("Product", where: "id=?", whereArgs: [id]);} 
}
  • 更改主要方法以获取产品信息。

void main() {runApp(MyApp(products: SQLiteDbProvider.db.getAllProducts())); 
}
  • 在这里,无涯教程使用了getAllProducts方法来从数据库中获取所有产品。

  • 运行该应用程序并查看结果。它与先前的示例访问产品服务API相似,不同之处在于,产品信息是从本地SQLite的数据库存储和获取的。

Flutter - 数据库 - 无涯教程网无涯教程网提供SQLite" class="css-1occaib">SQLite数据库是基于事实和标准SQL的嵌入式数据库引擎...https://www.learnfk.com/flutter/flutter-database-concepts.html

相关文章:

无涯教程-Flutter - 数据库

SQLite" class"css-1occaib">SQLite数据库是基于事实和标准SQL的嵌入式数据库引擎&#xff0c;它是小型且经过时间考验的数据库引擎&#xff0c;sqflite软件包提供了许多函数&#xff0c;可以有效地与SQLite数据库一起使用&#xff0c;它提供了操作SQLite数据…...

算法笔记:平衡二叉树

1 介绍 平衡二叉树&#xff08;AVL树&#xff09;是一种特殊的二叉搜索树&#xff08;BST&#xff09;&#xff0c;它自动确保树保持低高度&#xff0c;以便实现各种基本操作&#xff08;如添加、删除和查找&#xff09;的高效性能。 ——>时间都维持在了O(logN)它是一棵空…...

redis 通用命令

目录 通用命令是什么 SET & GET keys EXISTS DEL EXPIRE TTL redis 的过期策略 定时器策略 基于优先级队列定时器 基于时间轮的定时器 TYPE 通过 redis 客户端和 redis 服务器交互。 所以需要使用 redis 的命令&#xff0c;但是 redis 的命令非常多。 通用命令…...

Pycharm配置及使用Git教程

文章目录 1. 安装PyCharm2. 安装Git3. 在PyCharm中配置Git插件4. 连接远程Gtilab仓库5. Clone项目代码6. 将本地文件提交到远程仓库6.1 git add6.2 git commit6.3 git push6.4 git pull 平时习惯在windows下开发&#xff0c;但是我们又需要实时将远方仓库的代码clone到本地&…...

CSS transition 过渡

1 前言 水平居中、垂直居中是前端面试百问不厌的问题。 其实现方案也是多种多样&#xff0c;常叫人头昏眼花。 水平方向可以认为是内联方向&#xff0c;垂直方向认为是块级方向。 下面介绍一些常见的方法。 2 内联元素的水平垂直居中 首先&#xff0c;常见内联元素有&…...

Unity中Shader的UV扭曲效果的实现

文章目录 前言一、实现的思路1、在属性面板暴露一个 扭曲贴图的属性2、在片元结构体中&#xff0c;新增一个float2类型的变量&#xff0c;用于独立存储将用于扭曲的纹理的信息3、在顶点着色器中&#xff0c;根据需要使用TRANSFORM_TEX对Tilling 和 Offset 插值&#xff1b;以及…...

Automotive 添加一个特权APP

Automotive 添加一个特权APP platform: android-13.0.0_r32 一. 添加一个自定义空调的app为例 路径&#xff1a;packages/apps/Car/MyHvac app内容可以自己定义&#xff0c;目录结构如下&#xff1a; 1.1 Android.bp package {default_applicable_licenses: ["Andr…...

自定义TimeLine

自定义TimeLine 什么是TimeLineData&#xff08;数据&#xff09;Clip&#xff08;片段&#xff09;Track&#xff08;轨道&#xff09;Mixer&#xff08;混合&#xff09; 什么是TimeLine 在 Unity 中&#xff0c;TimeLine&#xff08;时间轴&#xff09;是一种用于创建和管理…...

如何使用SQL系列 之 如何在SQL中使用WHERE条件语句

引言 在结构化查询语言 (SQL)语句中&#xff0c;WHERE子句限制了给定操作会影响哪些行。它们通过定义特定的条件(称为搜索条件)来实现这一点&#xff0c;每一行都必须满足这些条件才能受到操作的影响。 本指南将介绍WHERE子句中使用的通用语法。它还将概述如何在单个WHERE子句…...

leetcode:1941. 检查是否所有字符出现次数相同(python3解法)

难度&#xff1a;简单 给你一个字符串 s &#xff0c;如果 s 是一个 好 字符串&#xff0c;请你返回 true &#xff0c;否则请返回 false 。 如果 s 中出现过的 所有 字符的出现次数 相同 &#xff0c;那么我们称字符串 s 是 好 字符串。 示例 1&#xff1a; 输入&#xff1a;s…...

Echarts 各种点击事件监听

目录 一、鼠标事件1.1、左击1.2、双击1.3、右击1.4、右键双击1.5、中轴滚动二、时间轴2.1、时间轴监听三、拖动3.1、拖动事件一、鼠标事件 1.1、左击 chart.on(click, function(params)...

《智能网联汽车自动驾驶功能测试规程》

一、 编制背景 2018 年4 月12 日&#xff0c;工业和信息化部、公安部、交通运输部联合发布《智能网联汽车道路测试管理规范(试行)》&#xff08;以下简称《管理规范》&#xff09;&#xff0c;对智能网联汽车道路测试申请、审核、管理以及测试主体、测试驾驶人和测试车辆要求等…...

NVIDIA CUDA Win10安装步骤

前言 windows10 版本安装 CUDA &#xff0c;首先需要下载两个安装包 CUDA toolkit&#xff08;toolkit就是指工具包&#xff09;cuDNN 1. 安装前准备 在安装CUDA之前&#xff0c;需要完成以下准备工作&#xff1a; 确认你的显卡已经正确安装&#xff0c;在设备管理器中可以看…...

Elasticsearch、Kibana以及Java操作ES 的快速使用

docker 安装elastic search 、 kibana&#xff08;可视化管理elastic search&#xff09; docker pull elasticsearch:7.12.1 docker pull kibana:7.12.1创建docker自定义网络 docker自定义网络可以使得容器之间使用容器名网络互连&#xff0c;默认的网络不会有这功能。 一定…...

逐鹿人形机器人,百度、腾讯、小米卷起来

长期不温不火的人形机器人产业迎来新风口&#xff0c;技术显著提升、新品层出不穷、资本投资态度也逐渐好转。 8月18日&#xff0c;2023世界机器人大会博览会正式开放&#xff0c;全面展示了机器人行业的新技术、新产品和新应用。据悉&#xff0c;此次展会展览总面积达4.5万平…...

AndroidStudio推荐下载和配置

1、推荐下载链接 Download Android Studio & App Tools - Android Developers 2、gradle配置案例 // Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {repositories {maven { url https://maven.aliyun.…...

mysql异常占用资源排查

通过执行日志与连接信息排查 查看是否开启日志记录 mysql> show global variables like %general%; --------------------------------- | Variable_name | Value | --------------------------------- | general_log | OFF | | general_log_file…...

requests 库:发送 form-data 格式的 http 请求 (python)

安装 requests-toolbelt !pip install requests-toolbeltdemo from requests_toolbelt import MultipartEncoder import requestsm MultipartEncoder(fields{query: """第一&#xff0c;向量化匹配是有能力上限的。搜索引擎实现语义搜索已经是好几年的事情了…...

行测图形推理规律(一)元素组成

题库&#xff1a;粉笔网题库 (fenbi.com) 不知道和测评的行测题库是不是一样的&#xff0c;但是总结的规律应该是一样的。 规律并不唯一&#xff0c;题库的答案也只是参考答案&#xff0c;切勿当杠精&#xff0c;你觉得你的规律更合适就别管。本人所归纳的规律仅代表本人想法…...

【python爬虫】13.吃什么不会胖(爬虫实操练习)

文章目录 前言项目实操明确目标分析过程代码实现 前言 吃什么不会胖——这是我前段时间在健身时比较关注的话题。 相信很多人&#xff0c;哪怕不健身&#xff0c;也会和我一样注重饮食的健康&#xff0c;在乎自己每天摄入的食物热量。 不过&#xff0c;生活中应该很少有人会…...

网络六边形受到攻击

大家读完觉得有帮助记得关注和点赞&#xff01;&#xff01;&#xff01; 抽象 现代智能交通系统 &#xff08;ITS&#xff09; 的一个关键要求是能够以安全、可靠和匿名的方式从互联车辆和移动设备收集地理参考数据。Nexagon 协议建立在 IETF 定位器/ID 分离协议 &#xff08;…...

业务系统对接大模型的基础方案:架构设计与关键步骤

业务系统对接大模型&#xff1a;架构设计与关键步骤 在当今数字化转型的浪潮中&#xff0c;大语言模型&#xff08;LLM&#xff09;已成为企业提升业务效率和创新能力的关键技术之一。将大模型集成到业务系统中&#xff0c;不仅可以优化用户体验&#xff0c;还能为业务决策提供…...

设计模式和设计原则回顾

设计模式和设计原则回顾 23种设计模式是设计原则的完美体现,设计原则设计原则是设计模式的理论基石, 设计模式 在经典的设计模式分类中(如《设计模式:可复用面向对象软件的基础》一书中),总共有23种设计模式,分为三大类: 一、创建型模式(5种) 1. 单例模式(Sing…...

家政维修平台实战20:权限设计

目录 1 获取工人信息2 搭建工人入口3 权限判断总结 目前我们已经搭建好了基础的用户体系&#xff0c;主要是分成几个表&#xff0c;用户表我们是记录用户的基础信息&#xff0c;包括手机、昵称、头像。而工人和员工各有各的表。那么就有一个问题&#xff0c;不同的角色&#xf…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

【单片机期末】单片机系统设计

主要内容&#xff1a;系统状态机&#xff0c;系统时基&#xff0c;系统需求分析&#xff0c;系统构建&#xff0c;系统状态流图 一、题目要求 二、绘制系统状态流图 题目&#xff1a;根据上述描述绘制系统状态流图&#xff0c;注明状态转移条件及方向。 三、利用定时器产生时…...

OPenCV CUDA模块图像处理-----对图像执行 均值漂移滤波(Mean Shift Filtering)函数meanShiftFiltering()

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 在 GPU 上对图像执行 均值漂移滤波&#xff08;Mean Shift Filtering&#xff09;&#xff0c;用于图像分割或平滑处理。 该函数将输入图像中的…...

Java多线程实现之Thread类深度解析

Java多线程实现之Thread类深度解析 一、多线程基础概念1.1 什么是线程1.2 多线程的优势1.3 Java多线程模型 二、Thread类的基本结构与构造函数2.1 Thread类的继承关系2.2 构造函数 三、创建和启动线程3.1 继承Thread类创建线程3.2 实现Runnable接口创建线程 四、Thread类的核心…...

LINUX 69 FTP 客服管理系统 man 5 /etc/vsftpd/vsftpd.conf

FTP 客服管理系统 实现kefu123登录&#xff0c;不允许匿名访问&#xff0c;kefu只能访问/data/kefu目录&#xff0c;不能查看其他目录 创建账号密码 useradd kefu echo 123|passwd -stdin kefu [rootcode caozx26420]# echo 123|passwd --stdin kefu 更改用户 kefu 的密码…...

QT3D学习笔记——圆台、圆锥

类名作用Qt3DWindow3D渲染窗口容器QEntity场景中的实体&#xff08;对象或容器&#xff09;QCamera控制观察视角QPointLight点光源QConeMesh圆锥几何网格QTransform控制实体的位置/旋转/缩放QPhongMaterialPhong光照材质&#xff08;定义颜色、反光等&#xff09;QFirstPersonC…...