Home > Net >  Parsing dynamic lists in flutter
Parsing dynamic lists in flutter

Time:11-08

I'm trying to parse a JSON data making API calls that is a series of objects wrapped inside a list.

[
  {
    "userId": 1,
    "id": 1,
    "title": "quidem molestiae enim"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "sunt qui excepturi placeat culpa"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "omnis laborum odio"
  },
  {
    "userId": 1,
    "id": 4,
    "title": "non esse culpa molestiae omnis sed optio"
  },
  {
    "userId": 1,
    "id": 5,
    "title": "eaque aut omnis a"
  },
  {
    "userId": 1,
    "id": 6,
    "title": "natus impedit quibusdam illo est"
  },
  {
    "userId": 1,
    "id": 7,
    "title": "quibusdam autem aliquid et et quia"
  },
]

And this is the widget on which I want the data to be rendered. I would also like to know if I have invoked the data from the json response correctly in the lines that I've commented :

import 'package:flutter/material.dart';
import '../widget/list.dart';
import '../model/data.dart';
import 'package:provider/provider.dart';

class MainScreen extends StatefulWidget {
  @override
  MainScreenState createState() => MainScreenState();
}

class MainScreenState extends State<MainScreen> {

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    Provider.of<DataModel>(context, listen: false).fetchData();
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<DataModel>(context).listData;
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("Profile App 2"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(5.0),
        child: ListView.builder(
          itemBuilder: (builder, index) => ListWidget(
            provider[index].userId, //to fetch the userId
            provider[index].id,     //to fetch the id
            provider[index].title   //to fetch the title
          ),
          itemCount: provider.length
        ),
      ),
    );
  }
}

The error now gets thrown against in the DataModel class at the lines commented 32:19 and 33:14:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Data {
  final int userId;
  final int id;
  final String title;

  Data({
    required this.userId,
    required this.id,
    required this.title
  });
}

class DataModel with ChangeNotifier {
  List<Data> _list = [];

  List<Data> get listData {
    return [..._list];
  }

  Future<void> fetchData() async {
    final url = Uri.parse('https://jsonplaceholder.typicode.com/albums');
    final response = await http.get(url);
    final extractedData = json.decode(response.body);
    print(extractedData);
    Map<String, Data> map = {};
    extractedData.forEach((value) => map.putIfAbsent(  //32:19
        value['id'], () => Data(                       //33:14
        userId: value['userId'],
        id: value['id'],
        title: value['title']
        )
      )
    );
    _list = map as List<Data>;
    notifyListeners();
  }
}   

The error:

E/flutter ( 9589): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'int' is not a subtype of type 'String'
E/flutter ( 9589): #0      DataModel.fetchData.<anonymous closure> (package:profile_api_2/model/data.dart:33:14)
E/flutter ( 9589): #1      List.forEach (dart:core-patch/growable_array.dart:403:8)
E/flutter ( 9589): #2      DataModel.fetchData (package:profile_api_2/model/data.dart:32:19)
E/flutter ( 9589): <asynchronous suspension>

CodePudding user response:

Change it to this:

final provider = Provider.of<DataModel>(context, listen: true);
.
.
.
.
//inside your listview builder, do this:

provider.listData[index].userId, //to fetch the userId
itemCount: provider.listData.length

CodePudding user response:

Try _list = map.values.toList(); instead of _list = map as List<Data> also now you have to use provider[index].userId instead of provider.values.toList()[index].userId.

CodePudding user response:

Please change datatype of your id or userId field of Data class. For some reason, it's unable to parse either id or userId as int or both. Please check by changing datatype to String one by one. Hope it will work.

  • Related