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

如何将API响应存入数据库?Flutter调用Restful API后存数据到sqlite的实现问题

前置准备:添加依赖

首先在项目的pubspec.yaml文件的dependencies区块添加以下三个依赖库:

  • http:用于发送网络请求,调用Restful API
  • sqflite:SQLite数据库操作封装库,简化本地数据库增删改查逻辑
  • path_provider:用于获取移动端本地存储路径,方便数据库文件存储
第一步:实现Restful API调用

先定义用户数据模型,再封装接口请求逻辑,示例代码如下:

import 'package:http/http.dart' as http;
import 'dart:convert';

// 用户信息Model,统一处理接口返回和数据库存储的字段映射
class User {
  final int id;
  final String name;
  final String email;

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

  // 接口返回JSON转User对象
  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
    );
  }

  // User对象转Map格式,适配数据库存储要求
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'email': email,
    };
  }
}

// 调用用户信息接口的方法
Future<User?> fetchUserInfo() async {
  final response = await http.get(Uri.parse('替换为你自己的用户信息接口地址'));
  // 判断接口返回状态码是否为200
  if (response.statusCode == 200) {
    return User.fromJson(jsonDecode(response.body));
  } else {
    // 非200状态可根据业务需求做错误处理,这里直接返回空
    return null;
  }
}
第二步:配置SQLite数据库

封装数据库初始化、插入数据的通用逻辑,示例代码如下:

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

class DatabaseHelper {
  // 单例模式,避免重复初始化数据库
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  static Database? _database;
  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  // 初始化数据库,创建用户信息表
  _initDatabase() async {
    final dir = await getApplicationDocumentsDirectory();
    final path = join(dir.path, 'user_database.db');
    return await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute('''
        CREATE TABLE users (
          id INTEGER PRIMARY KEY,
          name TEXT NOT NULL,
          email TEXT NOT NULL
        )
      ''');
    });
  }

  // 插入用户信息到数据库,同id用户重复插入时直接覆盖旧数据
  Future<int> insertUser(User user) async {
    final db = await instance.database;
    return await db.insert('users', user.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace);
  }
}
第三步:整合逻辑,请求成功后存储数据

在需要触发的业务位置调用以下逻辑即可完成需求:

void fetchAndSaveUser() async {
  User? user = await fetchUserInfo();
  if (user != null) {
    await DatabaseHelper.instance.insertUser(user);
    // 存储完成后可根据需求添加后续业务逻辑,比如提示存储成功
  }
}
注意事项
  • 实际使用时需要调整User类的字段、数据库表字段和接口返回字段保持一致,避免解析错误
  • 网络请求需要在Android的AndroidManifest.xml、iOS的Info.plist中配置对应网络权限,避免请求被系统拦截
  • 如果接口是POST请求,只需要调整http调用的方法和传参逻辑,数据库操作部分不需要改动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:54:09