Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

flutter - Passing class static factory as method parameter in Dart

I'm currently attempting to abstract making different HTTP requests by using generics. I'm using json_serializale for generating fromJson() and toJson() methods.

Here is a simple model file:

import 'package:json_annotation/json_annotation.dart';

part 'article.g.dart';

@JsonSerializable()
class Article {
  int id = 0;
  String title = "";

  Article({this.id, this.title});

  factory Article.fromJson(Map<String, dynamic> json) =>
      _$ArticleFromJson(json);
  Map<String, dynamic> toJson() => _$ArticleToJson(this);
}

I have a generic class that needs to be passed the fromJson-method, see:

typedef CreateModelFromJson = dynamic Function(Map<String, dynamic> json);

class HttpGet<Model> {
  CreateModelFromJson createModelFromJson;

  HttpGet({
    this.createModelFromJson,
  });

  Future<Model> do() async {
    // [... make HTTP request and do stuff ...]
    return createModelFromJson(jsonData);
  }
}

And finally, here is the ArticleService:

class ArticleService {
  Future<Model> read() => HttpGet<Article>({
    createModelFromJson: Article.fromJson,
  }).do();
}

This underlines-in-red fromJson in createModelFromJson: Article.fromJson,, with the error being:

The getter 'fromJson' isn't defined for the class 'Article'. Try importing the library that defines 'fromJson', correcting the name to the name of an existing getter, or defining a getter or field named 'fromJson'.dart(undefined_getter)

Obviously the compiler believes .fromJson to be a static field. However, it's, as can be seen above, a static factory method.

1.) Can you help with how to pass the constructor to the generic class?

ALSO:
2.) I'm not sure whether I'll actually get an Article back, or if I have to type cast it first? I'm kind of worried about the dynamic return type of the typedef.

3.) I'm also open for better ideas for what I'm attempting to do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Dart currently does not allow using constructors as tear-offs. I recommend using a static method instead.

Alternatively you could just create an explicit closure:

class ArticleService {
  Future<Model> read() => HttpGet<Article>({
    createModelFromJson: (json) => Article.fromJson(json),
  }).do();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.5k users

...