NumberFormat으로 가격 다루기
Coddy Flutter 여정의 데이터와 네트워크 섹션에 포함된 레슨. 27개 중 22번째.
가격은 서버에서 일반 숫자로 전달됩니다: 7.5, 12.25. 7.5를 문자열에 넣으면 $7.5가 되는데, 이렇게 인쇄하는 상점은 없습니다. 가격에는 통화 기호와 정확히 두 자리의 소수 자릿수가 필요합니다.
같은 intl 패키지에 있는 NumberFormat.currency는 두 가지를 모두 처리합니다:
final price = NumberFormat.currency(symbol: '\$');
price.format(7.5) // $7.50
price.format(1250) // $1,250.00통화 기호를 추가하고, 항상 소수 자릿수를 두 자리로 표시하며, 천 단위 사이에 쉼표를 넣습니다. symbol은 출력할 기호입니다. 지정하지 않으면 통화 코드가 대신 표시됩니다: USD7.50.
$ 기호 앞에는 백슬래시가 붙어 '\$'로 씁니다. Dart 문자열에서 $는 변수의 시작을 의미하기 때문입니다. 백슬래시는 "일반 달러 기호"라는 뜻입니다.
챌린지
쉬움책 가격은 $7.5로 표시됩니다. 모든 가격을 NumberFormat.currency(symbol: '\$')로 형식화하여 $8.99, $7.50, $12.25로 표시하세요.
직접 해보기
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'api.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: BooksScreen(),
);
}
}
class BooksScreen extends StatefulWidget {
const BooksScreen({super.key});
@override
State<BooksScreen> createState() => _BooksScreenState();
}
class _BooksScreenState extends State<BooksScreen> {
late Future<List<Book>> _books;
@override
void initState() {
super.initState();
_books = loadBooks();
}
Future<List<Book>> loadBooks() async {
final body = await fetch('/books');
final items = jsonDecode(body) as List<dynamic>;
return items.map((item) => Book.fromJson(item as Map<String, dynamic>)).toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Books')),
body: FutureBuilder<List<Book>>(
future: _books,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(child: Text('Could not load: ${snapshot.error}'));
}
if (snapshot.hasData) {
final books = snapshot.data!;
return ListView.builder(
itemCount: books.length,
itemBuilder: (context, index) {
final book = books[index];
return ListTile(
title: Text(book.title),
subtitle: Text(book.author),
trailing: Text(
'\$${book.price}',
style: const TextStyle(fontSize: 18),
),
);
},
);
}
return const Center(child: CircularProgressIndicator());
},
),
);
}
}
class Book {
Book({required this.title, required this.author, required this.price});
final String title;
final String author;
final double price;
factory Book.fromJson(Map<String, dynamic> json) {
return Book(
title: json['title'] as String,
author: json['author'] as String,
price: json['price'] as double,
);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
데이터와 네트워크의 모든 레슨
직접 연습해 보세요: 온라인 Flutter 컴파일러