IT 개발/앱

[왕초보] 플러터(Flutter)로 시작하는 앱개발 4주차 - 스파르타코딩클럽

르무엘 2023. 4. 11. 02:33

[왕초보] 플러터(Flutter)로 시작하는 앱개발 4주차 - 스파르타코딩클럽

 

 

[코드스니펫] 네이버 영어사전 URL https://en.dict.naver.com/#/search?query=hello&range=all

 

코드스니펫을 복사해 새 탭에서 접속해주세요. [코드스니펫] json 데이터 응답 URL https://jsonplaceholder.typicode.com/posts

코드스니펫을 복사해서 새 탭에서 열어주세요. [코드스니펫] JSON Viewer 확장 프로그램 URL https://chrome.google.com/webstore/detail/jsonview/gmegofmjomhknnokphhckolhcffdaihd?hl=ko

 

JSONView

브라우저에서 JSON 문서를 보세요.

chrome.google.com

 

HTTP 상태 코드 - HTTP | MDN (mozilla.org)

 

HTTP 상태 코드 - HTTP | MDN

HTTP 응답 상태 코드는 특정 HTTP 요청이 성공적으로 완료되었는지 알려줍니다. 응답은 5개의 그룹으로 나누어집니다: 정보를 제공하는 응답, 성공적인 응답, 리다이렉트, 클라이언트 에러, 그리고

developer.mozilla.org

 

[코드스니펫] google 책 검색 API문

볼륨: list  |  Google Books APIs  |  Google Developers

 

볼륨: list  |  Google Books APIs  |  Google Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 볼륨: list 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 도서검색을 수행합니다. 지금

developers.google.com

 

[코드스니펫] google 책 검색 API 예제 https://www.googleapis.com/books/v1/volumes?q=%EA%B3%A0%EC%96%91%EC%9D%B4

[코드스니펫] DartPad google 책 검색 API https://dartpad.dev/?id=1519f6b1a7ac26cf42e4e302750650e0

 

 

 [코드스니펫] DartPad async https://dartpad.dev/?id=1984d6cae83118a401f59f8f0034c8e4

 

DartPad

 

dartpad.dev

 

 

[코드스니펫] DartPad async & await https://dartpad.dev/?id=83d6c5a955cc9230d3f44ea5106236a7

 

DartPad

 

dartpad.dev

[코드스니펫] DartPad Future https://dartpad.dev/?id=a6734196a437a06985388c183dc78c4

 

DartPad

 

dartpad.dev

 

 [코드스니펫] provider 패키지 설치 flutter pub add provider

 

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'book_service.dart';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => BookService()),
],
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
var bottomNavIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: [
SearchPage(),
LikedBookPage(),
].elementAt(bottomNavIndex),
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: Colors.black,
unselectedItemColor: Colors.grey,
showUnselectedLabels: true,
selectedFontSize: 12,
unselectedFontSize: 12,
iconSize: 28,
type: BottomNavigationBarType.fixed,
onTap: (value) {
setState(() {
bottomNavIndex = value;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: '검색',
),
BottomNavigationBarItem(
icon: Icon(Icons.star),
label: '좋아요',
),
],
currentIndex: bottomNavIndex,
),
);
}
}
class SearchPage extends StatelessWidget {
SearchPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
toolbarHeight: 80,
title: TextField(
onSubmitted: (value) {},
cursorColor: Colors.grey,
decoration: InputDecoration(
prefixIcon: Icon(Icons.search, color: Colors.grey),
hintText: "작품, 감독, 배우, 컬렉션, 유저 등",
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.grey),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
),
),
),
body: Center(
child: Text("검색"),
),
);
}
}
class LikedBookPage extends StatelessWidget {
const LikedBookPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text("좋아요"),
),
);
}
}

 

코드스니펫을 복사해 새 탭에서 열어주세요. [코드스니펫] Pub.dev / dio / Installing https://pub.dev/packages/dio/install

 

dio | Dart Package

A powerful HTTP package for Dart/Flutter, which supports Global settings, Interceptors, FormData, Aborting and canceling a request, Files uploading and downloading, Requests timeout, Custom adapters, etc.

pub.dev

 

코드스니펫을 복사해 새 탭에서 열어주세요. [코드스니펫] Pub.dev / dio / Installing https://pub.dev/packages/dio/install

 

dio | Dart Package

A powerful HTTP package for Dart/Flutter, which supports Global settings, Interceptors, FormData, Aborting and canceling a request, Files uploading and downloading, Requests timeout, Custom adapters, etc.

pub.dev

 

erminal 창에 복사한 flutter pub add dio 를 붙여넣고 엔터를 눌러 실행해 주세요. 아래와 같이 나오면 정상적으로 작동한 것입니다.

 

pubspec.yaml 파일을 열어서 아래와 같이 40번째 라인에 dio 가 있으면 설치가 완료된 것입니다.

 

main() async { Response result = await Dio().get("URL"); print(result.data); // data 안에 응답 내용이 들어 있습니다. }

 

[코드스니펫] google 책 검색 API 예제 https://www.googleapis.com/books/v1/volumes?q=%EA%B3%A0%EC%96%91%EC%9D%B4

 

Google Book API에 대한 자세한 사항은 아래 코드스니펫 링크를 참고해주세요. [코드스니펫] Google Book API 문서 https://developers.google.com/books/docs/v1/reference/volumes/list

 

볼륨: list  |  Google Books APIs  |  Google Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 볼륨: list 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 도서검색을 수행합니다. 지금

developers.google.com

 

for (Map<string, dynamic=""> item in items) { Book book = Book( id: item['id'], title: item['volumeInfo']['title'] ?? "", subtitle: item['volumeInfo']['subtitle'] ?? "", thumbnail: item['volumeInfo']['imageLinks']?['thumbnail'] ?? "https://thumbs.dreamstime.com/b/no-image-available-icon-flat-vector-no-image-available-icon-flat-vector-illustration-132482953.jpg", previewLink: item['volumeInfo']['previewLink'] ?? "", ); bookList.add(book); }</string,>

 

[코드스니펫] bookList 비우기

 

[코드스니펫] SearchPage / ListView.builder

body: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: ListView.separated(
              itemCount: bookService.bookList.length,
              separatorBuilder: (context, index) {
                return Divider();
              },
              itemBuilder: (context, index) {
                Book book = bookService.bookList.elementAt(index);
                return ListTile();
              },
            ),
          ),

 

return ListTile(
                  onTap: () {},
                  leading: Image.network(
                    book.thumbnail,
                    fit: BoxFit.fitHeight,
                  ),
                  title: Text(
                    book.title,
                    style: TextStyle(fontSize: 16),
                  ),
                  subtitle: Text(
                    book.subtitle,
                    style: TextStyle(color: Colors.grey),
                  ),
                  trailing: IconButton(
                    onPressed: () {},
                    icon: Icon(Icons.star_border),
                  ),
                );

 


                if (bookService.bookList.isEmpty) return SizedBox();

 


  List<Book> likedBookList = [];

 



  void toggleLikeBook({required Book book}) {
    String bookId = book.id;
    if (likedBookList.map((book) => book.id).contains(bookId)) {
      likedBookList.removeWhere((book) => book.id == bookId);
    } else {
      likedBookList.add(book);
    }
    notifyListeners();
  }

 


    BookService bookService = context.read<BookService>();

 

onPressed: () {
          bookService.toggleLikeBook(book: book);
        },
        icon: bookService.likedBookList.map((book) => book.id).contains(book.id)
            ? Icon(
                Icons.star,
                color: Colors.amber,
              )
            : Icon(Icons.star_border),

 

body: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12),
            child: ListView.separated(
              itemCount: bookService.bookList.length,
              separatorBuilder: (context, index) {
                return Divider();
              },
              itemBuilder: (context, index) {
                if (bookService.bookList.isEmpty) return SizedBox();
                Book book = bookService.bookList.elementAt(index);
                return BookTile(book: book);
              },
            ),
          ),

 

https://pub.dev/packages/webview_flutter

 

webview_flutter | Flutter Package

A Flutter plugin that provides a WebView widget on Android and iOS.

pub.dev

[코드스니펫] Pub.dev / webview_flutter

flutter pub add webview_flutter:^3.0.4

 

https://brunch.co.kr/@hyoi0303/10

 

HTTP와 HTTPS 차이점

디자이너가 개발자와 일 하다 보니 (2) | 지난 2014년 구글에서는 HTTP를 HTTPS로 바꾸라고 권고한다. 그전까지는 전자상거래가 있는 웹 사이트에서만 다소 번거로운 HTTPS를 사용하고 있었다. HTTPS로

brunch.co.kr

 

LIST