커뮤니티
포인트
쿠폰
내 강의실
국비 신청 내역
증명서
계정
로그아웃
학습 질문
개발 일지
나의 활동
답변 완료
watcha_pedia 기능 구현 : 검색 후 코드를 새로고침 해야만 화면 반영
앱개발 종합반 - 플러터
4주차
북마크
전*연
댓글
4
추천
0
조회수
25
조회수
25
답변 완료

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

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


  • 왓챠피디아 숙제 기능까지 구현 완료한 상태인데, 다른 것들은 잘 돌아가는데 검색버튼을 누를때만 바로 화면이 새로고침되지 않고, 코드에서 새로고침을 해야 반영됩니다.
  • 키보드에 입력 후 검색버튼 클릭 > 화면 그대로 > 코드파일에서 저장 (Cmd+S) > (다른 것 클릭안해도) 화면 새로고침되면서 검색됨



1. Cat 입력 후 검색버튼 클릭 시 : 콘솔창에 '검색버튼 누름'은 뜨는데 화면 새로고침이 안됩니다.

스파르타 즉문즉답


2. 코드파일에서 저장 (cmd+S)만 하면 다른 동작안해도 화면이 새로고침되면서 리스트가 나옵니다.

스파르타 즉문즉답



작성한 코드 및 에러


book.dart

class Book {
  String id;
  String title;
  String subtitle;
  String thumbnail;
  String previewLink;
  List author;
  String publishedDate;


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


  Map toJson() {
    return {
      'id': id,
      'title': title,
      'subtitle': subtitle,
      'thumbnail': thumbnail,
      'previewLink': previewLink,
      'author': author,
      'publishedDate': publishedDate,
    };
  }


  factory Book.fromJson(json) {
    return Book(
      id: json['id'],
      title: json['title'],
      subtitle: json['subtitle'],
      thumbnail: json['thumbnail'],
      previewLink: json['previewLink'],
      author: json['author'],
      publishedDate: json['publishedDate'],
    );
  }
}



book_service.dart

// ignore_for_file: avoid_print


import 'dart:convert';


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


import 'book.dart';


class BookService extends ChangeNotifier {
  BookService() {
    loadLikedBookList();
  }
  List<Book> bookList = []; // 책 목록
  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();
    saveLikedBookList();
  }


  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'] ?? "",
          author: item['volumeInfo']['authors'] ?? "",
          publishedDate: item['volumeInfo']['publishedDate'] ?? "",
        );
        bookList.add(book);
        print('검색버튼 누름');
      }
    }
    notifyListeners();
    saveLikedBookList();
  }


  saveLikedBookList() {
    List likedBookJsonList =
        likedBookList.map((book) => book.toJson()).toList();
    String jsonString = jsonEncode(likedBookJsonList);


    prefs.setString('likedBookList', jsonString);
  }


  loadLikedBookList() {
    String? jsonString = prefs.getString('likedBookList');


    if (jsonString == null) return;


    List likedBookJsonList = jsonDecode(jsonString);


    likedBookList =
        likedBookJsonList.map((json) => Book.fromJson(json)).toList();
  }
}


main.dart

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


import 'book.dart';
import 'book_service.dart';


late SharedPreferences prefs;


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  prefs = await SharedPreferences.getInstance();
  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) {
                //키보드에서 done을 클릭했을 때 검색필드 값을 전달
                //print(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 BookTile(book: book);
              },
            ),
          ));
    });
  }
}


class BookTile extends StatelessWidget {
  const BookTile({
    Key? key,
    required this.book,
  }) : super(key: key);


  final Book book;


  @override
  Widget build(BuildContext context) {
    BookService bookService = context.read<BookService>();
    return ListTile(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => WebViewPage(
              url: book.previewLink.replaceFirst("http", "https"),
            ),
          ),
        );
      },
      leading: Image.network(
        book.thumbnail,
        fit: BoxFit.fitHeight,
      ),
      title: Text(
        book.title,
        style: TextStyle(fontSize: 16),
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            book.author.join(", "),
            style: TextStyle(color: Colors.grey),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
          Text(
            book.publishedDate,
            style: TextStyle(color: Colors.grey),
          ),
          /*Text(
            book.subtitle,
            style: TextStyle(color: Colors.grey),
          ),*/
        ],
      ),
      trailing: IconButton(
          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)),
    );
  }
}


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


  @override
  Widget build(BuildContext context) {
    return Consumer<BookService>(
      builder: (context, bookService, child) {
        return Scaffold(
            body: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12),
          child: ListView.separated(
            itemCount: bookService.likedBookList.length,
            separatorBuilder: (context, index) {
              return Divider();
            },
            itemBuilder: (context, index) {
              if (bookService.likedBookList.isEmpty) return SizedBox();
              Book book = bookService.likedBookList.elementAt(index);
              return BookTile(book: book);
            },
          ),
        ));
      },
    );
  }
}


class WebViewPage extends StatelessWidget {
  WebViewPage({super.key, required this.url});


  String url;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.grey,
        title: Text(url),
      ),
      body: WebView(initialUrl: url), //webview_flutter 패키지에서 제공해주는 위젯
    );
  }
}


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