How to perform get request with request parameter using provider flutter

Viewed 14

Hi all am trying to perform a get request by passing a parameter and trying to display it on a page

everything is working I can able to get the data and call it in page load but the problem is how to display it in the page when I try to call it says undefined

please help me with a solution

where this is my API class

Future<AlbumModel> fetchAlbum(int id) async {
  final response = await http.get(
      Uri.parse('https://jsonplaceholder.typicode.com/posts/' + id.toString()));

  if (response.statusCode == 200) {
    print(response.body);
    return AlbumModel.fromJson(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load post');
  }
}

my provider class

class GetAlbumData with ChangeNotifier {
  Future getAlbumById(int id) async {
    http.Response response = (await getAlbumById(id))!;
    if (response.statusCode == 200) {
      AlbumModel data = AlbumModel.fromJson(jsonDecode(response.body));
      notifyListeners();

      return data;
    }
  }
}

implementation class

class People extends StatefulWidget {
  final int id;
  const People({Key? key, required this.id}) : super(key: key);

  @override
  State<People> createState() => _PeopleState();
}

class _PeopleState extends State<People> {
  late Future<AlbumModel> futureAlbum;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getdata();
  }

  getdata() {
    var fetchData = Provider.of<GetAlbumData>(context, listen: false);
    fetchData.getAlbumById(widget.id);
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Theme.of(context).colorScheme.onBackground,
        body: Column(
          children: [
            const SizedBox(
              height: 50,
            ),
            Text(
              widget.id.toString(),
              style: const TextStyle(color: Colors.black, fontSize: 44),
            ),
          ],
        ),
      ),
    );
  }
}
0 Answers
Related