Home > Blockchain >  The argument type 'List<Widget>?' can't be assigned to the parameter type '
The argument type 'List<Widget>?' can't be assigned to the parameter type '

Time:08-19

i am trying to fill Gridview.count with result of list map

Here the code of dart class from json https://pastebin.com/ndvsfmEC

I would like to fill a GridView with the result from json but when I try to generate the data using map the message "The argument type 'List<Widget>?' can't be assigned to the parameter type 'List<Widget>'" appears for me.

Here the code where I try to fill gridview

var url = "https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json";

  PokeHub? pokeHub;

  Future fetchData() async {
    var response = await http.get(Uri.parse(url));
    var jsonData = jsonDecode(response.body);
    pokeHub = PokeHub.fromJson(jsonData);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Pokemon App'),
        backgroundColor: Colors.cyan,
      ),
      body: GridView.count(
          crossAxisCount: 2,
          children: pokeHub?.pokemon?.map<Widget>((e) => Card(child: Text(e.name),)).toList()
      ),
      drawer: Drawer(),
      floatingActionButton: FloatingActionButton(
        onPressed: (){},
        backgroundColor: Colors.cyan,
        child: Icon(Icons.refresh),
      ),
    );
  }

CodePudding user response:

body: GridView.count(
          crossAxisCount: 2,
          children: pokeHub?.pokemon?.map<Widget>((e) => Card(child: Text(e.name),)).toList()
      ),

By adding a ? In pokehub you mentioned that it's nullable which cannot be returned as a widget. You can fix it by adding an alternative if null

body: GridView.count(
          crossAxisCount: 2,
          children: pokeHub?.pokemon?.map<Widget>((e) => Card(child: Text(e.name),)).toList() ?? []
      ),

CodePudding user response:

Depending on what you want to achieve you can try something like this

body: pokeHub != null && pokeHub!.pokemon != null ? 
GridView.count(
      crossAxisCount: 2,
      children: pokeHub!.pokemon!.map<Widget>((e) => Card(child: Text(e.name),)).toList()), :
      const CircularProgressIndicator(),
  • Related