参数类型 'List<Plants>?' 无法分配给参数类型 'List<Plants>'
The argument type 'List<Plants>?' can't be assigned to the parameter type 'List<Plants>'
Widget build(BuildContext context) => Scaffold(
body: FutureBuilder<List<Plants>>(
future: PlantsApi.getPlantsLocally(context),
builder:(context, snapshot) {
final users = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Center(child: Text('Some error'),);
}
else {
return buildPlants(users);
}
}
},
),
);
我对这个有误。用户是错误
当我将 buildPlants(users)
更改为 buildPlants(users!)
时,出现此错误:
Error: Member not found: 'fromJson'.
return body.map<Plants>(Plants.fromJson).toList();
^^^^^^^^
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:oplantapp/model/plantData.dart';
class PlantsApi {
static Future<List<Plants>> getPlantsLocally(BuildContext context) async {
final assetBundle = DefaultAssetBundle.of(context);
final data = await assetBundle.loadString('assets/plants.json');
final body = json.decode(data);
return body.map<Plants>(Plants.fromJson).toList();
}
}
这是我获取的数据
我认为您没有在 Plants class 中实现 Plants.fromJson
方法。参考 official documentation
...
Plants.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
...
在 Plants 中实施 Plants.fromJson
方法后。尝试更改您的 return 语句
return body.map<Plants>((e) => Plants.fromJson(e)).toList();
Widget build(BuildContext context) => Scaffold(
body: FutureBuilder<List<Plants>>(
future: PlantsApi.getPlantsLocally(context),
builder:(context, snapshot) {
final users = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Center(child: Text('Some error'),);
}
else {
return buildPlants(users);
}
}
},
),
);
我对这个有误。用户是错误
当我将 buildPlants(users)
更改为 buildPlants(users!)
时,出现此错误:
Error: Member not found: 'fromJson'.
return body.map<Plants>(Plants.fromJson).toList();
^^^^^^^^
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'package:oplantapp/model/plantData.dart';
class PlantsApi {
static Future<List<Plants>> getPlantsLocally(BuildContext context) async {
final assetBundle = DefaultAssetBundle.of(context);
final data = await assetBundle.loadString('assets/plants.json');
final body = json.decode(data);
return body.map<Plants>(Plants.fromJson).toList();
}
}
这是我获取的数据
我认为您没有在 Plants class 中实现 Plants.fromJson
方法。参考 official documentation
...
Plants.fromJson(Map<String, dynamic> json)
: name = json['name'],
email = json['email'];
...
在 Plants 中实施 Plants.fromJson
方法后。尝试更改您的 return 语句
return body.map<Plants>((e) => Plants.fromJson(e)).toList();