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

Flutter中如何从SQLite获取单条记录并存储到模型类中使用

Flutter SQLite 获取单条记录并映射到模型展示

1. 定义模型类

先创建与数据库表对应的模型类,实现从SQLite查询结果的Map转换为模型实例的方法:

class User {
  final int id;
  final String name;
  final String email;

  User({required this.id, required this.name, required this.email});

  // 把SQLite返回的Map转成User实例
  factory User.fromMap(Map<String, dynamic> map) {
    return User(
      id: map['id'],
      name: map['name'],
      email: map['email'],
    );
  }
}

2. 实现数据库查询方法

在你的SQLite操作类中,添加获取单条记录的方法,通过ID(或其他条件)查询并返回模型实例:

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;

  DatabaseHelper._init();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB('users.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future<void> _createDB(Database db, int version) async {
    await db.execute('''
      CREATE TABLE users(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT NOT NULL UNIQUE
      )
    ''');
  }

  // 获取单条用户记录
  Future<User?> getSingleUser(int userId) async {
    final db = await instance.database;
    // 按ID查询,limit 1确保只返回一条结果
    final maps = await db.query(
      'users',
      where: 'id = ?',
      whereArgs: [userId],
      limit: 1,
    );

    return maps.isNotEmpty ? User.fromMap(maps.first) : null;
  }
}

3. 在Widget中获取并展示数据

使用FutureBuilder处理异步查询,然后在Text组件中展示模型数据:

import 'package:flutter/material.dart';

class UserDetailScreen extends StatelessWidget {
  final int userId;

  const UserDetailScreen({super.key, required this.userId});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('用户详情')),
      body: FutureBuilder<User?>(
        future: DatabaseHelper.instance.getSingleUser(userId),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('获取数据失败: ${snapshot.error}'));
          } else if (!snapshot.hasData || snapshot.data == null) {
            return const Center(child: Text('未找到该用户'));
          } else {
            final user = snapshot.data!;
            return Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('ID: ${user.id}', style: const TextStyle(fontSize: 18)),
                  const SizedBox(height: 8),
                  Text('姓名: ${user.name}', style: const TextStyle(fontSize: 18)),
                  const SizedBox(height: 8),
                  Text('邮箱: ${user.email}', style: const TextStyle(fontSize: 18)),
                ],
              ),
            );
          }
        },
      ),
    );
  }
}

注意事项

  • 确保SQLite表结构和模型类字段完全对应,避免字段名不匹配导致转换失败
  • 必须处理异步状态:加载中、错误、无数据的情况,提升用户体验
  • 若查询条件不是ID,可修改where和whereArgs参数适配你的业务需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:49:56