Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
1
Indexable
Never
import 'dart:convert';

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

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Data?> lists = [];
  @override
  void initState() {
    super.initState();
    getData().then((value) {
      if (value != null && value.data != null) {
        setState(() {
          lists = value.data!.cast<Data?>();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: lists.length,
        itemBuilder: (context, index) {
          var item = lists[index];
          return ListTile(
            title: Text('${item?.firstName} - ${item?.lastName}'),
            subtitle: Text('${item?.email}'),
            leading: Text('${item?.id}'),
          );
        },
      ),
    );
  }

  Future<DemoModel?> getData() async {
    const url = 'https://reqres.in/api/users?page=2';
    var response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      var jsonBody = DemoModel.fromJson(jsonDecode(response.body));
      return jsonBody;
    } else {
      print('Something Wrong...');
    }
  }
}