Prices With NumberFormat
Part of the Data and the Network section of Coddy's Flutter journey. Lesson 22 of 27.
Prices come from servers as plain numbers: 7.5, 12.25. Put 7.5 in a string and you get $7.5, which no shop would print. A price needs its currency sign and exactly two decimals.
NumberFormat.currency, from the same intl package, does both:
final price = NumberFormat.currency(symbol: '\$');
price.format(7.5) // $7.50
price.format(1250) // $1,250.00It adds the sign, always writes two decimals, and puts commas between thousands. symbol is the sign to print. Without it you get the currency's code instead: USD7.50.
The $ sign has a backslash in front, '\$', because in a Dart string $ starts a variable. The backslash says "a plain dollar sign".
Challenge
EasyThe book prices read $7.5. Format every price with NumberFormat.currency(symbol: '\$'), so they read $8.99, $7.50 and $12.25.
Try it yourself
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,
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and the Network
Practice on your own: Online Flutter compiler