Home > OS >  The element type 'Future<List<Organization>>?' can't be assigned to the l
The element type 'Future<List<Organization>>?' can't be assigned to the l

Time:08-03

class Organization_Api{
    static Future<List<dynamic>> getData(
      {required String target, String? limit}) async {
    try {
      var uri = Uri.https(
          BASE_URL,
          "api/$target",
          target == "organizations"
              ? {
            "offset": "0",
            "limit": limit,
          }
              : {});
      var response = await http.get(uri);
      var data = jsonDecode(response.body);
      List tempList = [];
      if (response.statusCode != 200) {
        throw data["message"];
      }
      for (var v in data) {
        tempList.add(v);
      }
      return tempList;
    } catch (error) {
      log("An error occured $error");
      throw error.toString();
    }
  }
   
    static Future<List<Organization>> getAllOrganizations(
      {required String limit}) async {
    List temp = await getData(
      target: "organizations",
      limit: limit,
    );
    return Organization.organizationsToList(temp);
  }
  
     static Future<Organization> getOrganizationById({required String id}) async {
    try {
      var uri = Uri.https(
        BASE_URL,
        "api/organizations/$id",
      );
      var response = await http.get(uri);
      var data = jsonDecode(response.body);
      if (response.statusCode != 200) {
        throw data["message"];
      }
      return Organization.fromJson(data);
    } catch (error) {
      log("an error occured while getting organization info $error");
      throw error.toString();
    }
  }
}
 class HomeScreen extends StatefulWidget {
    const HomeScreen({Key? key}) : super(key: key);
    static String routeName = "/home";
    @override
    State<HomeScreen> createState() => _HomeScreenState();
}

    class _HomeScreenState extends State<HomeScreen> {
    Future<List<Organization>>? result ;
    void initState(){
    result = Organization_Api.getAllOrganizations(limit: '4');
    super.initState();
  }

    @override
    Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Organizations", style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Padding(
        padding: EdgeInsets.all(10.0),
        child: Column(
          children:
            <Widget>[
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children:<Widget>[
                    ListView(
                      shrinkWrap: true,
                      children:<Widget> [result],
                    )
                  ],
                ),
              )
          ],
        ),
      ),
    );
  }
}

class Organization{
  final int OrganizationId;
  final String OrganizationName;

  Organization({required this.OrganizationId,required this.OrganizationName});

  factory Organization.fromJson(Map<String,dynamic> json){
    return Organization(OrganizationId: json['OrganizationId'], OrganizationName: json['OrganizationName']);
  }
  Map toJson(){
    return{
      "OrganizationId": this.OrganizationId,
      "OrganizationName": this.OrganizationName,
    };
  }
  static List<Organization> organizationsToList(List organizationToList) {
    return organizationToList.map((data) {
      return Organization.fromJson(data);
    }).toList();
  }
}

Error = The element type >'Future<List>?' can't be assigned to the list type 'Widget'.

I just want to check the data coming from the service, but I couldn't find how to do it. What did I do wrong or what did I miss to list the incoming data? I shared the screen page and the codes on how I got the information from the service.

CodePudding user response:

Your Organization_Api.getAllOrganizations provide a future. You can use FutureBuilder.

class _HomeScreenState extends State<HomeScreen> {
  Future<List<Organization>>? myFuture;

  @override
  void initState() {
    myFuture = Organization_Api.getAllOrganizations(limit: '4');
    super.initState();
  }

And on future builder

FutureBuilder<List<Organization>?>(
  future: myFuture,
  builder: (context, snapshot) {
    if (snapshot.hasData && snapshot.data!.isNotEmpty) {
      return ListView(
        shrinkWrap: true,
        //children: snapshot.data!, // when `Organization` is a widget
        children:// when `Organization` is a data model class
        snapshot.data!.map((e) => Text(e.toString())).toList(),
      );
    }

    return CircularProgressIndicator();
  },
)

Also check Randal L. Schwartz video on using Future

  • Related