[Flutter] http , Hero , 애니메이션 전환, Url launcher

merci·2023년 4월 9일
0

fetch 레퍼런스 코드 ( http )

class WebtoonEpisodeModel {
  final String id, title, rating, date;

  WebtoonEpisodeModel.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        title = json['title'],
        rating = json['rating'],
        date = json['date'];
}

  static Future<WebtoonDetailModel> getToonById(String id) async {
    final url = Uri.parse("$baseUrl/$id");
    final response = await http.get(url);
    if (response.statusCode == 200) {
      final webtoon = jsonDecode(response.body);
      return WebtoonDetailModel.fromJson(webtoon);
    }
    throw Error();
  }

  static Future<List<WebtoonEpisodeModel>> getLatestEpisodesById(
      String id) async {
    List<WebtoonEpisodeModel> episodesInstances = [];
    final url = Uri.parse("$baseUrl/$id/episodes");
    final response = await http.get(url);
    if (response.statusCode == 200) {
      final episodes = jsonDecode(response.body);
      for (var episode in episodes) {
        episodesInstances.add(WebtoonEpisodeModel.fromJson(episode));
      }
      return episodesInstances;
    }
    throw Error();
  }

응답 헤더를 확인하는 방법

import 'package:http/http.dart' as http;

void main() async {
  final url = 'https://your.api.endpoint.com/data'; // Replace with your actual API endpoint URL

  final response = await http.get(
    Uri.parse(url),
  );

  if (response.statusCode == 200) {
    print('Response headers:');
    response.headers.forEach((name, values) {
      print('$name: $values');
    });

    print('Response body:');
    print(response.body);
  } else {
    print('Error: ${response.statusCode}');
  }
}

받은 jwt를 헤더에 넣어 요청보내기

import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  final jwt = 'your.jwt.string'; // Replace with your actual JWT string
  final url = 'https://your.api.endpoint.com/data'; // Replace with your actual API endpoint URL

  final response = await http.get(
    Uri.parse(url),
    headers: {
      'Authorization': 'Bearer $jwt',
      'Content-Type': 'application/json',
    },
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    print(data);
  } else {
    print('Error: ${response.statusCode}');
  }
}

커스텀한 애니메이션으로 화면전환하는 방법

Navigator.push(
  context,
  PageRouteBuilder(
    pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
      // Define your custom page widget here
      return MyCustomPageWidget();
    },
    transitionDuration: Duration(milliseconds: 500), // Set the duration of the animation
    transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
      // Define your custom animation here
      return FadeTransition(
        opacity: animation,
        child: child,
      );
    },
  ),
);

Hero 위젯

누른 사진이 화면에 유지된다. 위젯을 Hero로 감싸고 tag:id, 를 추가하면 된다.

첫번째 페이지의 이미지( 주로 컨테이너 ), 와 라우팅된 페이지의 이미지( 주로 컨테이너 ) 를 Hero 위젯으로 감싼뒤 tag 를 추가한다.

Hero(
  tag: 'heroTag',
  child: ... // 전환될 위젯
)

url lancher

의존성 추가

url_launcher: ^6.1.10

manifest 권한 추가 ( 일단 안드로이드만 )

하위에 추가

    <!-- Provide required visibility configuration for API level 30 and above -->
    <queries>
        <!-- If your app checks for SMS support -->
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="sms" />
        </intent>
        <!-- If your app checks for call support -->
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="tel" />
        </intent>
    </queries>

본문에 아래 코드 추가하면 버튼으로 외부 페이지를 연결하거나 전화를 걸고 이메일을 보낼수 있게 된다.

// 연결할 홈페이지 주소 
final Uri _url = Uri.parse('https://flutter.dev');

// 버튼을 클릭했을때 함수 호출
const Center(
      child: ElevatedButton(
        onPressed: _launchUrl,
        child: Text('Show Flutter homepage'),
      ),
    ),
     
// 비동기로 화면 열기
Future<void> _launchUrl() async {
  if (!await launchUrl(_url)) {
    throw Exception('Could not launch $_url');
  }
}

전화를 건다면?

class _MyHome4State extends State<MyHome4> {
  bool _hasCallSupport = false;
  Future<void>? _launched;
  final String _phone = '전화번호 여기에 입력';
  
  
  void initState() {
    super.initState();
    // Check for phone call support.
    canLaunchUrl(Uri(scheme: 'tel', path: '123')).then((bool result) {
      setState(() {
        _hasCallSupport = result;
      });
    });
  }
  
    Future<void> _makePhoneCall(String phoneNumber) async {
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    await launchUrl(launchUri);
  }
  
  // 전화 버튼
  
  ElevatedButton(
  onPressed: _hasCallSupport
      ? () => setState(() {
            _launched = _makePhoneCall(_phone);
          })
      : null,
  child: _hasCallSupport
      ? const Text('Make phone call')
      : const Text('Calling not supported'),
),
profile
작은것부터

0개의 댓글