Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.04 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:http/http.dart' as http;
  3. import 'dart:convert';
  4.  
  5. void main() => runApp(new MyApp());
  6.  
  7. class MyApp extends StatefulWidget {
  8.   @override
  9.   _MyAppState createState() => _MyAppState();
  10. }
  11.  
  12. class _MyAppState extends State<MyApp> {
  13.   String name, username, avatar;
  14.   bool isData = false;
  15.  
  16.   FetchJSON() async {
  17.     var Response = await http.get(
  18.       "https://api.github.com/users/nitishk72",
  19.       headers: {"Accept": "application/json"},
  20.     );
  21.  
  22.     if (Response.statusCode == 200) {
  23.       String responseBody = Response.body;
  24.       var responseJSON = json.decode(responseBody);
  25.       username = responseJSON['login'];
  26.       name = responseJSON['name'];
  27.       avatar = responseJSON['avatar_url'];
  28.       isData = true;
  29.       setState(() {
  30.         print('UI Updated');
  31.       });
  32.     } else {
  33.       print('Something went wrong. \nResponse Code : ${Response.statusCode}');
  34.     }
  35.   }
  36.  
  37.   @override
  38.   void initState() {
  39.     FetchJSON();
  40.   }
  41.  
  42.   Widget MyUI() {
  43.     return new Container(
  44.       padding: new EdgeInsets.all(20.0),
  45.       child: new ListView(
  46.         children: <Widget>[
  47.           new Image.network(
  48.             avatar,
  49.             width: 100.0,
  50.             height: 100.0,
  51.           ),
  52.           new Padding(padding: new EdgeInsets.symmetric(vertical: 6.0)),
  53.           new Text(
  54.             'Name : $name',
  55.             style: Theme.of(context).textTheme.headline,
  56.           ),
  57.           new Padding(padding: new EdgeInsets.symmetric(vertical: 6.0)),
  58.           new Text(
  59.             'Username : $username',
  60.             style: Theme.of(context).textTheme.title,
  61.           ),
  62.         ],
  63.       ),
  64.     );
  65.   }
  66.  
  67.   @override
  68.   Widget build(BuildContext context) {
  69.     return new MaterialApp(
  70.       home: new Scaffold(
  71.         appBar: new AppBar(
  72.           title: new Text('Fetch JSON'),
  73.         ),
  74.         body: isData
  75.             ? new Center(
  76.                 child: new CircularProgressIndicator(),
  77.               )
  78.             : MyUI(),
  79.       ),
  80.     );
  81.   }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement