Home > Software design >  The argument type 'List<Plants>?' can't be assigned to the parameter type '
The argument type 'List<Plants>?' can't be assigned to the parameter type '

Time:10-25

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);
          }
        }
      }, 
    ),
  );

I'm having error with this one. the users is the error

when I change the buildPlants(users) to buildPlants(users!) I get this error:

 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();
  }
}

here is my fetch data

CodePudding user response:

I think you didn't implement Plants.fromJson method in your Plants class. Refer official documentation

...
Plants.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];
...

After implementing Plants.fromJson method in Plants. Try to change your return statement

return body.map<Plants>((e) => Plants.fromJson(e)).toList();
  • Related