Flutter SQFlite Class 到 Json()

Flutter SQFlite Class to Json()

我目前正在开发一款用户可以在其设备上本地存储数据的应用程序。因此,我正在使用 sqflite 包,但在将我的 Class 数据转换为 Json 时出现了一些错误 运行。 这是我收到的错误消息:

A value of type 'Set' can't be returned from the method 'toJson' because it has a return type of 'Map<String, Widget>'. due to this line:

Map<String, Widget> toJson() => {
            EntryFields.id = id,
            EntryFields.name = name,
            EntryFields.navigation = navigation,
          };

这是我的 class:

import 'package:flutter/material.dart';

const String tableFavs = 'favorites';

class EntryFields {
  static late String id = '_id';
  static late String name = '_name';
  static late String navigation = '_navigation';
}

class Entries {
  final int id;
  final String name;
  final Widget navigation;

  Entries({
    required this.id,
    required this.name,
    required this.navigation,
  });

  Map<String, Widget> toJson() => {
        EntryFields.id = id,
        EntryFields.name = name,
        EntryFields.navigation = navigation,
      };
}

这是从我的数据库中截取的:

  Future<Entries> create(Entries entries) async {
    final db = await instance.database;

    final id = await db.insert(tableFavs, entries.toJson());
  }

您不能将小部件存储在数据库中,它应该是 Map 尝试将小部件的参数存储为字符串,而不是整个小部件 你可以存储这些类型 double, string, int, bool..

尝试使用下面的代码

class EntryFields {
  static late String id = '_id';
  static late String name = '_name';
  static late String navigation = '_navigation';
}

class Entries {
    const Entries({
        this.id,
        this.name,
        this.navigation,
    });

    final String? id;
    final String? name;
    final String? navigation;

    Map<String, dynamic> toJson() => {
        "_id": id,
        "_name": name,
        "_navigation": navigation,
    };
}

  Future<void> create(Entries entries) async {
    final db = await instance.database;
    final id = await db.insert(tableFavs, entries.toJson());
  }

void main(){
  final entriesFromField = Entries(
    id: EntryFields.id,
    name: EntryFields.name,
    navigation: EntryFields.navigation
  );
  
  create(entriesFromField);
  
}

或者更好的是你可以使用这个json generator