dart Flutter数据:使用保存()时model.key为null

vc9ivgsu  于 2023-07-31  发布在  Flutter
关注(0)|答案(1)|浏览(119)

我正在使用flutter_data包从ws本地保存数据。
我使用remoteAdatper.save()来保存从API获取的数据(使用http请求),但我在这里得到了一个Unhandled Exception: Null check operator used on a null value

res.results.forEach((element) {
      element.save(element, remote: false);
});

个字符
有人能告诉我我哪里做错了吗?
这里是我的课程:

mixin PlaceAdapter<T extends DataModelMixin<T>> on RemoteAdapter<T> {

  @override
  Future<T> save(
    model, {
    bool? remote,
    Map<String, dynamic>? params,
    Map<String, String>? headers,
    Object? onSuccess,
    Object? onError,
    DataRequestLabel? label,
  }) {
    return super.save(model, remote: false);
  }
}
@freezed
@DataRepository([PlaceAdapter])
class Place with DataModelMixin<Place>, _$Place {
  Place._();

  factory Place({
    required String id,
    required String name,
    required String address,
  }) = _Place;

  factory Place.fromJson(Map<String, Object?> json) => _$PlaceFromJson(json);
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ProviderScope(
      overrides: [
        configureRepositoryLocalStorage(
          // callback that returns a base directory where to place local storage
          // (if the path_provider package is present, otherwise you MUST override it)
          baseDirFn: () async => getApplicationDocumentsDirectory().then((dir) => dir.path),
        ),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        navigatorKey: StackedService.navigatorKey,
        onGenerateRoute: StackedRouter().onGenerateRoute,
        home: Splashscreen(),
      ),
    );
  }
}
exdqitrt

exdqitrt1#

我终于找到了解决办法。我将适配器更改为:

mixin PlaceAdapter<T extends DataModel<T>> on RemoteAdapter<T> {

  @override
  Future<T> save(
    model, {
    bool? remote,
    Map<String, dynamic>? params,
    Map<String, String>? headers,
    Object? onSuccess,
    Object? onError,
    DataRequestLabel? label,
  }) {
    return super.save(model, remote: false);
  }
}

字符串
然后在我的模型类中使用DataModel而不是DataModelMixin
我不知道为什么,但这很有效。如果有人有解释,请随意发表评论。

相关问题