
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
4주차 숙제 중입니다.
2번째 숙제 진행중인데 아래와 같은 에러가 뜹니다.
LateInitializationError: Field 'prefs' has not been initialized.
작성한 코드 및 에러 메세지
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();
SharedPreferences 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;
List authors;
String publishedDate;// ListTile 을 눌렀을 때 이동하는 링크
Book({
required this.title,
required this.id,
required this.subtitle,
required this.thumbnail,
required this.previewLink,
required this.authors,
required this.publishedDate,
});
Map toJson() {
return {
'title' : title,
'id' : id,
'subtitle' : subtitle,
'thumbnail' : thumbnail,
'previewLink' : previewLink,
'authors' : authors,
'publishedDate' : publishedDate
};
}
factory Book.fromJson(json){
return Book(
title: json['title'],
id: json['id'],
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(){
loadLikeBook();
}
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();
saveLikeBook();
}
saveLikeBook(){
List likeJsonList = likedBookList.map((book) => book.toJson()).toList();
String jsonString = jsonEncode(likeJsonList);
prefs.setString(('likeBookList'), jsonString);
}
loadLikeBook(){
String? jsonString = prefs.getString('likeBookList');
if (jsonString == null) return;
List likeJsonList = jsonDecode(jsonString);
likedBookList = likeJsonList.map((json) => Book.fromJson(json)).toList();
}
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'] ?? "",
authors: item['volumeInfo']['authors'] ?? [],
publishedDate: item['volumeInfo']['publishedDate'] ?? "",
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();
}
}
에러
Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app-debug.apk...
Debug service listening on ws://127.0.0.1:2764/f9kW7Oi59jM=/ws
Syncing files to device sdk gphone64 x86 64...
======== Exception caught by widgets library =======================================================
The following LateError was thrown building Consumer<BookService>(dirty, dependencies: [_InheritedProviderScope<BookService?>]):
LateInitializationError: Field 'prefs' has not been initialized.
The relevant error-causing widget was:
Consumer<BookService> Consumer:file:///C:/Users/PC/Desktop/watcha_pedia/lib/main.dart:86:12
When the exception was thrown, this was the stack:
#0 prefs (package:watcha_pedia/main.dart)
#1 BookService.loadLikeBook (package:watcha_pedia/book_service.dart:36:26)
#2 new BookService (package:watcha_pedia/book_service.dart:11:5)
#3 main.<anonymous closure> (package:watcha_pedia/main.dart:17:53)
#4 _CreateInheritedProviderState.value (package:provider/src/inherited_provider.dart:736:36)
#5 _InheritedProviderScopeElement.value (package:provider/src/inherited_provider.dart:590:33)
#6 Provider.of (package:provider/src/provider.dart:303:37)
#7 Consumer.buildWithChild (package:provider/src/consumer.dart:181:16)
#8 SingleChildStatelessWidget.build (package:nested/nested.dart:259:41)
#9 StatelessElement.build (package:flutter/src/widgets/framework.dart:5156:49)
#10 SingleChildStatelessElement.build (package:nested/nested.dart:279:18)
#11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5086:15)
#12 Element.rebuild (package:flutter/src/widgets/framework.dart:4805:7)
#13 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:5068:5)
#14 ComponentElement.mount (package:flutter/src/widgets/framework.dart:5062:5)
#15 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:222:11)
... Normal element mounting (31 frames)
#46 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3971:16)
#47 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6570:36)
#48 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6582:32)
... Normal element mounting (332 frames)
#380 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3971:16)
#381 MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6570:36)
#382 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6582:32)
... Normal element mounting (432 frames)
#814 _InheritedProviderScopeElement.mount (package:provider/src/inherited_provider.dart:411:11)
... Normal element mounting (7 frames)
#821 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:222:11)
... Normal element mounting (7 frames)
#828 _NestedHookElement.mount (package:nested/nested.dart:187:11)
... Normal element mounting (7 frames)
#835 SingleChildWidgetElementMixin.mount (package:nested/nested.dart:222:11)
... Normal element mounting (27 frames)
#862 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3971:16)
#863 Element.updateChild (package:flutter/src/widgets/framework.dart:3708:18)
#864 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1240:16)
#865 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1209:5)
#866 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1156:18)
#867 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2720:19)
#868 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1155:13)
#869 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:988:7)
#870 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:968:7)
#874 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:189:12)
(elided 3 frames from class _Timer and dart:async-patch)
====================================================================================================
