[flutter] http Json list가져오기

박망키·2022년 8월 3일
1

Flutter 야금야금 먹기

목록 보기
58/97

정보를 뭉텅이로 가져오기

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

class Info {
  final int id;
  final String userName;
  final int account;
  final int balance;

  Info(
      {required this.id,
      required this.userName,
      required this.account,
      required this.balance});

  factory Info.fromJson(Map<String, dynamic> json) {
    return Info(
      id: json["id"],
      userName: json["userName"],
      account: json["account"],
      balance: json["balance"],
    );
  }
}

Future<List<Info>> fetchInfo() async {
  var url = 'https://api.mockaroo.com/api/5ee43e50?count=10&key=6213f2b0';
  final response = await http.post(Uri.parse(url));

  if (response.statusCode == 200) {
    //만약 서버가 ok응답을 반환하면, json을 파싱합니다
    print('응답했다');
    print(json.decode(response.body));
    List<dynamic> body = json.decode(response.body);
    List<Info> allInfo =
        body.map((dynamic item) => Info.fromJson(item)).toList();

    return allInfo;
  } else {
    //만약 응답이 ok가 아니면 에러를 던집니다.
    throw Exception('불러오는데 실패했습니다');
  }
}

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

  @override
  State<TestPage> createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  Future<List<Info>>? info;
  Future<List<Info>>? clickedInfo;

  @override
  void initState() {
    super.initState();
    info = fetchInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('info', style: TextStyle(color: Colors.white)),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          child: Center(
            child: Column(
              children: [
                FutureBuilder<List<Info>>(
                  //통신데이터 가져오기
                  future: info,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return buildList(snapshot.data);
                    } else if (snapshot.hasError) {
                      return Text("${snapshot.error}에러!!");
                    }
                    return CircularProgressIndicator();
                  },
                ),
              ],
            ),
          ),
        ));
  }

  Widget buildList(snapshot) {
    return SizedBox(
      height: 150,
      child: ScrollConfiguration(
        behavior: MyCustomScrollBehavior(),
        child: ListView.builder(
            itemCount: snapshot.length,
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, i) {
              return Container(
                decoration: BoxDecoration(color: Colors.red.shade100),
                margin: EdgeInsets.symmetric(horizontal: 1),
                height: 150,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text('고객번호:' + snapshot[i].id.toString(),
                        style: TextStyle(fontSize: 20)),
                    Text('고객명:' + snapshot[i].userName.toString(),
                        style: TextStyle(fontSize: 20)),
                    Text('계좌 아이디:' + snapshot[i].account.toString(),
                        style: TextStyle(fontSize: 20)),
                    Text('잔액:' + snapshot[i].balance.toString() + '원',
                        style: TextStyle(fontSize: 20)),
                  ],
                ),
              );
            }),
      ),
    );
  }
}

class MyCustomScrollBehavior extends MaterialScrollBehavior {
  // Override behavior methods and getters like dragDevices
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
        // etc.
      };
}

결과

profile
무럭무럭 자라는 망키

0개의 댓글