
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
안녕하세요 튜터님 !
4주차 숙제를 하면서
코드 상에는 따로 에러(빨간줄)가 있다고는 안 뜨는데
에뮬레이터에는 뭔가 에러가 났다고 표시가 되는 것 같습니다.
구글링을 해도 해결하기가 쉽지 않아 도움 요청 드립니다 !
(관련 파일 코드들 아래에 첨부드립니다.)

Debug Console
Launching lib\main.dart on Android SDK built for x86 in debug mode...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:61152/eGG43j9epjo=/ws
I/le.watcha_pedi(10524): Waiting for a blocking GC ProfileSaver
════════ Exception caught by widgets library ═══════════════════════════════════
The following FormatException was thrown building Consumer<BookService>(dirty, dependencies: [_InheritedProviderScope<BookService?>]):
Unexpected character (at character 1)
jsonString
^
The relevant error-causing widget was
Consumer<BookService>
When the exception was thrown, this was the stack
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
#1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1250:9)
#2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:915:22)
#3 _parseJson (dart:convert-patch/convert_patch.dart:35:10)
#4 JsonDecoder.convert (dart:convert/json.dart:612:36)
#5 JsonCodec.decode (dart:convert/json.dart:216:41)
#6 jsonDecode (dart:convert/json.dart:155:10)
#7 BookService.loadLikedBooklist
#8 new BookService
#9 main.<anonymous closure>
#10 _CreateInheritedProviderState.value
#11 _InheritedProviderScopeElement.value
#12 Provider.of
#13 Consumer.buildWithChild
#14 SingleChildStatelessWidget.build
#15 StatelessElement.build
#16 SingleChildStatelessElement.build
#17 ComponentElement.performRebuild
#18 Element.rebuild
#19 ComponentElement._firstBuild
#20 ComponentElement.mount
#21 SingleChildWidgetElementMixin.mount
... Normal element mounting (31 frames)
#52 Element.inflateWidget
#53 MultiChildRenderObjectElement.inflateWidget
#54 MultiChildRenderObjectElement.mount
... Normal element mounting (387 frames)
#441 Element.inflateWidget
#442 MultiChildRenderObjectElement.inflateWidget
#443 MultiChildRenderObjectElement.mount
... Normal element mounting (413 frames)
#856 _InheritedProviderScopeElement.mount
... Normal element mounting (7 frames)
#863 SingleChildWidgetElementMixin.mount
... Normal element mounting (7 frames)
#870 _NestedHookElement.mount
... Normal element mounting (7 frames)
#877 SingleChildWidgetElementMixin.mount
#878 Element.inflateWidget
#879 Element.updateChild
#880 RenderObjectToWidgetElement._rebuild
#881 RenderObjectToWidgetElement.mount
#882 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure>
#883 BuildOwner.buildScope
#884 RenderObjectToWidgetAdapter.attachToRenderTree
#885 WidgetsBinding.attachRootWidget
#886 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure>
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════
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) {
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),
),
subtitle: Text(
"${book.authors.join(", ")}\n${book.publishedDate}",
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),
);
}
}
book.dart
class Book {
String id;
String title;
String subtitle;
String thumbnail; // 썸네일 이미지 링크
String previewLink; // ListTile 을 눌렀을 때 이동하는 링크
List authors;
String publishedDate;
Book({
required this.id,
required this.title,
required this.subtitle,
required this.thumbnail,
required this.previewLink,
required this.authors,
required this.publishedDate,
});
Map toJson() => {
'id': id,
'title': title,
'subtitle': subtitle,
'thumbnail': thumbnail,
'previewLink': previewLink,
'authors': authors,
'publishedDate': publishedDate,
};
factory Book.fromJson(json) {
return Book(
id: json['id'],
title: json['title'],
subtitle: json['subtitle'],
thumbnail: json['thumbnail'],
previewLink: json['previewLink'],
authors: json['authors'],
publishedDate: json['publishedDate'],
);
}
}
book_service.dart
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'book.dart';
import 'main.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'] ?? "",
authors: item['volumeInfo']['authors'] ?? "",
publishedDate: item['volumeInfo']['publishedDate'] ?? "",
);
bookList.add(book);
}
}
notifyListeners();
}
saveLikedBooklist() {
List likedJsonList = likedBookList.map((book) => book.toJson()).toList();
String jsonString = jsonEncode(likedJsonList);
prefs.setString('likedBookList', jsonString);
}
loadLikedBooklist() {
String? jsonString = prefs.getString('likedBookList');
if (jsonString == null) return;
List likedJsonList = jsonDecode('jsonString');
likedBookList = likedJsonList.map((json) => Book.fromJson(json)).toList();
}
}
