7

I'm currently building a Flutter app which fetches data from an Api, but when I run the application I'm getting the error Flutter 'List' is not a subtype of type 'Map<String, dynamic>'.Here is my code

    class NewsData with ChangeNotifier 
{

  Map<String,dynamic> _map = {};
  bool _error = false;
  String _errorMessage = '';

  Map<String,dynamic> get map => _map;
  bool get error => _error;
  String get errorMessage => _errorMessage;

  Future<void> get fetchdata async {
    final response = await get(Uri.parse('https://script.google.com/macros/s/AKfycbz3ZmaMiTgR-y70MEE1v9VPz2QtmNzwnnnnnnn/exec'),);
   if (response.statusCode == 200)
    {
    try
     {
       _map = jsonDecode(response.body);
       _error = false;
     }
     catch(e) {
       _error = true;
       _errorMessage = e.toString();
       _map = {};
     }
   }
   else
   {
    _error = true; 
    _errorMessage = 'Error :it could be your internet connection ';
       _map = {};
   }
    notifyListeners();
  }
  void initialValues()
  {
    _map = {};
    _error = false;
    _errorMessage = '';
     notifyListeners();
  }
}


stories.dart

class Storiespage extends StatelessWidget {
  const Storiespage({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    context.read<NewsData>().fetchdata;
    return Scaffold(
     appBar: AppBar(
       actions: [
         IconButton(
           icon: Icon(Icons.refresh),
           onPressed:() {
             context.read<NewsData>().initialValues();
              context.read<NewsData>().fetchdata;
           },
         )
       ],
       title: Text('ggg'),
     ),
     body: RefreshIndicator(
       onRefresh: () async {
        await context.read<NewsData>().fetchdata;
       },
       child: Center(
        child: Consumer<NewsData>(
        builder: (context, value, child) {
          return value.map.length == 0 && !value.error 
          ? CircularProgressIndicator() 
          : value.error ? Text('oops,something went wrong ${value.errorMessage}'
          ,textAlign: TextAlign.center,) : 
          ListView.builder(
            itemCount: value.map['feedback'].length,
            itemBuilder: (context,index) {
            
            
            return Newscard(map: value.map['feedback'][index]);
          },
          );
        },
        ),
       ),
     ), 
    );
  }
}

class Newscard extends StatelessWidget {
  const Newscard({ Key? key,required this.map }) : super(key: key);
final Map<String,dynamic> map;
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Card(
        elevation:10 ,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.network('${map['image']}'),
            SizedBox(
              height: 10,
            ),
            Text('${map['heading']}'
            ),
           SizedBox(
              height: 10,
            ),
              Text('${map['story']}'
            ),
            ],
            
          ),
        ),
      ),
    );
  }
}

and json file [ {"heading":"admire","story":2021,"date":" WORLD ","image":"01/A0000/06"},{"heading":"admire","story":2021,"date":" WORLD ","image":"01/A0000/06"},{"heading":"heading","story":"story","date":"date","image":"image"}]

3 Answers 3

10

The error occurs because your API returns a List as you can see in your json file. After you use jsonDecode your type of the decoding is List<dynamic>. To fix your issue you have to change the type of _map to List<dynamic>. If you want to have the type List<Map<String, dynamic>> you can do the following.

List<Map<String, dynamic>> map = [];
...
_map = List<Map<String, dynamic>>.from(jsonDecode(response.body));
Sign up to request clarification or add additional context in comments.

Comments

0

Just change map<String,dynamic> to List<dynamic> and you are good to go.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

Your _map Variable is of type Map<String, dynamic>, which means it can be used to store a single map element, consisting of key value pairs.

The result of jsonDecode of the response is of type List<Map>. So change the declaration of _map to

List<Map<String,dynamic>> _map;

OR simply

List _map;

OR

var _map;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.