카테고리 없음

dio패키지

신승호. 2023. 2. 17. 01:56

dio 패키지를 활용하여, 스나이퍼팩토리에 존재하는 비밀 URL을 찾아 호출하시오.

"https://sniperfactory.com/sfac/http_{20부터 50사이정수}"
  • ex) 0이라면, http_0으로 요청할 것
  • 반드시 반복문을 통하여 해결할 것. 이 때, 무한반복문이 되지 않도록 할 것.
import 'package:dio/dio.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  void getDataUsingDio() async {
    var dio = Dio();
    for (var i = 20; i <= 50; i++) {
      await dio
          .get(url + i.toString())
          .then((value) => print(url + i.toString()))
          .catchError((_) {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
            child: TextButton(
          onPressed: () {
            return getDataUsingDio();
          },
          child: Text('버튼누름'),
        )),
      ),
    );
  }
}

then()의 콜백은 Future가 값과 함께 종료된 경우 실행되며, catchError()의 콜백은 Future가 에러와 함께 종료된 경우 실행된다.

연속된 then(), catchError() 호출은 Future를 처리하기 위한 일반적인 패턴이다

결과

[참고]

https://terry1213.github.io/dart/dart-futures-and-error-handling/