Untitled

repo_list.dart
mail@pastecode.io avatar
unknown
dart
2 years ago
2.9 kB
2
Indexable
Never
import 'package:api_deneme/models/repo.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class RepoList extends StatefulWidget {
  const RepoList({Key? key}) : super(key: key);

  @override
  State<RepoList> createState() => _RepoListState();
}

Future<All> fetchRepos() async {
  final response =
      await http.get(Uri.parse('https://api.github.com/users/MuazzezA/repos'));

  if (response.statusCode == 200) {
    print(response.body + "\n");
    return All.fromJson(json.decode(response.body));
  } else {
    throw Exception('failed');
  }
}

class _RepoListState extends State<RepoList> {
  Future<All>? futureRepo;

  @override
  void initState() {
    super.initState();
    futureRepo = fetchRepos();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("github api deneme 1"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Container(
          child: buildRepoList(context),
        ),
      ),
    );
  }

  FutureBuilder buildRepoList(BuildContext context) {
    return FutureBuilder<All>(
      future: futureRepo,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          List<Repo> repos = <Repo>[];

          for (int i = 0; i < snapshot.data!.repos!.length; i++) {
            repos.add(Repo(
              name: snapshot.data!.repos![i].name,
              description: snapshot.data!.repos![i].description,
              htmlUrl: snapshot.data!.repos![i].htmlUrl,
              stargazerCount: snapshot.data!.repos![i].stargazerCount,
            ));

            return ListView(
              children: repos
                  .map(
                    (e) => Card(
                      color: Colors.blueGrey[100],
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(e.name! + "\n"),
                          Text("Description " + e.description!),
                          Text("Star " + e.stargazerCount.toString()),
                          Text(e.htmlUrl == null
                              ? 'Html ${e.htmlUrl}'
                              : 'html url'),
                        ],
                      ),
                    ),
                  )
                  .toList(),
            );
          }
        } else if (snapshot.hasError) {
          return const Center(child: Text('has error'));
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        return const Center(child: Text('has error 2'));
      },
    );
  }
}