커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
검색 결과가 뜨질 않네요...ㅠㅠ
[왕초보] 플러터(Flutter)로 시작하는 앱개발 종합반 v0
4주차
북마크
이*진
댓글
15
추천
1
조회수
21
조회수
21
답변 완료

* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.

* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.


코딩 자체엔 문제가 없는 것 같은데 다시 코드 점검해봐도 이렇다할 문제는 없다 생각해 관련 문의도 찾아보았지만 해결되지 않았어요...

에뮬을 껏다 다시 켜도 마찬가지로 검색결과 창이 뜨지 않습니다.



스파르타 즉문즉답




키보드 입력 시 디버그 콘솔 전문

Launching lib\main.dart on Android SDK built for x86 in debug mode...

main.dart:1
√  Built build\app\outputs\flutter-apk\app-debug.apk.

Connecting to VM Service at ws://127.0.0.1:60937/0zyMcvDjOPE=/ws

D/eglCodecCommon(15741): setVertexArrayObject: set vao to 0 (0) 1 0

D/EGL_emulation(15741): eglMakeCurrent: 0xf4f548e0: ver 2 0 (tinfo 0xde7d66f0)

D/eglCodecCommon(15741): setVertexArrayObject: set vao to 0 (0) 1 0

I/AssistStructure(15741): Flattened final assist data: 540 bytes, containing 1 windows, 3 viewsBoo

main_dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';


import 'book.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 Consumer<BookService>(
      builder: (context, bookService, child) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.white,
            toolbarHeight: 80,
            title: TextField(
              onSubmitted: (value) {
                bookService.search(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: 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 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),
                  ),
                );
              },
            ),
          ),
        );
      },
    );
  }
}


class LikedBookPage extends StatelessWidget {
  const LikedBookPage({super.key});


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("좋아요"),
      ),
    );
  }
}


book.dart

class Book {
  String id;
  String title;
  String subtitle;
  String thumbnail; // 썸네일 이미지 링크
  String previewLink; // ListTile 을 눌렀을 때 이동하는 링크


  Book({
    required this.id,
    required this.title,
    required this.subtitle,
    required this.thumbnail,
    required this.previewLink,
  });
}


book_service.dart

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';


import 'book.dart';


class BookService extends ChangeNotifier {
  List<Book> bookList = [];
  void search(String q) async {
    bookList.clear(); // 검색 버튼 누를때 이전 데이터들을 지워주기


    if (q.isNotEmpty) {
      Response res = await Dio().get(
        "https://www.googleapis.com/books/v1/volumes?q=$q&startIndex=0&maxResults=40",
      );
      List items = res.data["items"];


      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);
      }
    }
    notifyListeners();
  } // 책 목록
}


취소
 공유
취소
댓글 0
댓글 알림
나의얼굴