Professional Documents
Culture Documents
1
Bài 1: Cộng 2 số
Code:
import 'package:flutter/material.dart'; // Import thư viện flutter
void main() {
runApp(MyApp()); // Khởi chạy ứng dụng MyApp
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Calculator'), // Tiêu đề của ứng dụng
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
2
controller: number1Controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: 'Enter number
1'), // TextField nhập số thứ nhất
),
TextField(
controller: number2Controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(labelText: 'Enter number
2'), // TextField nhập số thứ hai
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
calculateSum(); // Gọi hàm tính tổng khi nhấn nút
},
child: Text('Calculate Sum'), // Nút tính tổng
),
SizedBox(height: 20),
Text('Result: $result'), // Kết quả tính toán
],
),
),
);
}
3
Bài 2: Calculator
Code:
import 'dart:math'; // Import thư viện dart:math
import 'package:flutter/material.dart'; // Import thư viện flutter
void main() {
runApp(CalculatorApp()); // Khởi chạy ứng dụng CalculatorApp
}
4
void _buttonPressed(String buttonText) {
setState(() {
if (isResultDisplayed && buttonText != '=') {
_output = '0';
isResultDisplayed = false;
}
if (buttonText == 'C') {
_output = '0';
_num1 = 0;
_num2 = 0;
_operator = '';
_previousResult = 0; // Xóa kết quả trước đó
} else if (isResultDisplayed && buttonText != '=') {
_output = '0';
isResultDisplayed = false;
} else if (buttonText == '+' ||
buttonText == '-' ||
buttonText == '*' ||
buttonText == '/') {
_num1 = double.parse(_output);
_operator = buttonText;
_output = '0';
} else if (buttonText == '=') {
_num2 = double.parse(_output);
if (_operator == '+') {
_output = (_num1 + _num2).toString();
} else if (_operator == '-') {
_output = (_num1 - _num2).toString();
} else if (_operator == '*') {
_output = (_num1 * _num2).toString();
} else if (_operator == '/') {
_output = (_num1 / _num2).toString();
}
if (_output.contains('.') &&
double.parse(_output) == double.parse(_output.split('.')
[0])) {
_output = int.parse(_output.split('.')[0]).toString();
}
5
isResultDisplayed = true;
} else if (buttonText == '√') {
_num1 = double.parse(_output);
_output = sqrt(_num1).toString();
} else if (buttonText == 'x^2') {
_num1 = double.parse(_output);
_output = (_num1 * _num1).toString();
} else if (buttonText == '⌫') {
// Xử lý xóa một chữ số
if (_output.length > 1) {
_output = _output.substring(0, _output.length - 1);
} else {
_output = '0';
}
} else {
if (_output == '0' && buttonText != '.') {
_output = buttonText;
} else if (buttonText == '.' && !_output.contains('.')) {
_output += buttonText;
} else if (buttonText != '.') {
_output += buttonText;
}
}
});
}
6
style: TextStyle(fontSize: 15.0, color: textColor),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Mai Đông Thức - Mã Quang Lộc',
style: TextStyle(fontSize: 20.0),
),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Container(
alignment: Alignment.bottomRight,
padding: EdgeInsets.all(24.0),
color: Colors.grey[200],
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
_previousResult.toString(),
style: TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.grey,
),
),
SizedBox(height: 8.0),
Text(
_output,
style: TextStyle(
fontSize: 48.0,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
],
),
7
),
),
Divider(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildButton('√', Colors.grey[300]!, Colors.black),
_buildButton('x^2', Colors.grey[300]!, Colors.black),
_buildButton('⌫', Colors.grey[300]!, Colors.black),
_buildButton('/', Colors.orange, Colors.white),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildButton('7', Colors.grey[300]!, Colors.black),
_buildButton('8', Colors.grey[300]!, Colors.black),
_buildButton('9', Colors.grey[300]!, Colors.black),
_buildButton('*', Colors.orange, Colors.white),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildButton('4', Colors.grey[300]!, Colors.black),
_buildButton('5', Colors.grey[300]!, Colors.black),
_buildButton('6', Colors.grey[300]!, Colors.black),
_buildButton('-', Colors.orange, Colors.white),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildButton('1', Colors.grey[300]!, Colors.black),
_buildButton('2', Colors.grey[300]!, Colors.black),
_buildButton('3', Colors.grey[300]!, Colors.black),
_buildButton('+', Colors.orange, Colors.white),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildButton('C', Colors.red, Colors.white),
_buildButton('0', Colors.grey[300]!, Colors.black),
_buildButton('.', Colors.grey[300]!, Colors.black),
_buildButton('=', Colors.blue, Colors.white),
8
],
),
],
),
);
}
}
9
Bài 3: Đồng hồ 3 kim
Code:
import 'dart:async'; // Import thư viện cho việc sử dụng Timer
import 'dart:math'; // Import thư viện cho việc sử dụng hàm cos và sin
import 'package:flutter/material.dart'; // Import thư viện flutter
void main() {
runApp(MyClockApp()); // Khởi chạy ứng dụng Flutter
}
10
@override
void initState() {
super.initState();
_timer = Timer.periodic(Duration(seconds: 1), _updateTime); // Cập
nhật thời gian mỗi giây
}
@override
void dispose() {
_timer?.cancel(); // Hủy timer khi widget bị huỷ
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
width: 300, // Chiều rộng của đồng hồ
height: 300, // Chiều cao của đồng hồ
child: CustomPaint(
painter: ClockPainter(_currentTime), // Vẽ đồng hồ
),
);
}
}
ClockPainter(this.time);
@override
void paint(Canvas canvas, Size size) {
final centerX = size.width / 2; // Tọa độ x của tâm đồng hồ
final centerY = size.height / 2; // Tọa độ y của tâm đồng hồ
final center = Offset(centerX, centerY); // Tọa độ tâm đồng hồ
11
..color = Color.fromARGB(255, 40, 255, 86) // Màu viền đồng hồ
..style = PaintingStyle.stroke // Kiểu vẽ là nét kẻ
..strokeWidth = 20; // Độ dày của viền
canvas.drawCircle(
center, radius + 5, borderPaint); // Vẽ đường viền mặt đồng hồ
(thêm 5 để đẩy viền ra ngoài)
// Vẽ mặt đồng hồ
final facePaint = Paint()
..color = Color.fromARGB(255, 59, 79, 60) // Màu mặt đồng hồ
..style = PaintingStyle.fill; // Kiểu vẽ là toàn phần
12
final endX = centerX + cos(angle) * radius; // Tọa độ x của điểm
kết thúc
final endY = centerY + sin(angle) * radius; // Tọa độ y của điểm
kết thúc
if (i % 5 == 0) {
// Nếu là số giờ, vẽ đường chính lớn
canvas.drawLine(
Offset(startX, startY), Offset(endX, endY),
mainLinePaint);
} else {
// Nếu không, vẽ đường nhỏ giữa các số
canvas.drawLine(
Offset(startX, startY), Offset(endX, endY),
smallLinePaint);
}
}
13
centerX + cos(hourAngle) * hourIndexRadius, // Tọa độ x của
điểm chỉ số
centerY + sin(hourAngle) * hourIndexRadius, // Tọa độ y của
điểm chỉ số
);
// Vẽ số giờ
textPainter.paint(
canvas,
Offset(
hourIndexOffset.dx - textPainter.width / 2, // Vị trí x của
số giờ
hourIndexOffset.dy - textPainter.height / 2, // Vị trí y của
số giờ
),
);
}
// Vẽ thứ ngày
_drawDateAndDay(canvas, centerX, centerY, radius);
14
'${_formatTwoDigits(hours)} : ${_formatTwoDigits(minutes)}';
// Chuỗi hiển thị thời gian
digitalTimePainter.layout();
15
textDirection: TextDirection.ltr,
);
datePainter.layout();
// Vẽ kim phút
final minutePaint = Paint()
..color = Colors.blue // Màu của kim phút
..style = PaintingStyle.stroke // Kiểu vẽ là nét kẻ
..strokeCap = StrokeCap.round // Kiểu đầu của kim phút
..strokeWidth = 10; // Độ dày của kim phút
final minuteAngle =
((time.minute + time.second / 60) - 15) * 6 * (pi / 180); //
Tính góc của kim phút
canvas.drawLine(
center,
center +
Offset(
16
cos(minuteAngle) * radius * 0.7, sin(minuteAngle) *
radius * 0.7),
minutePaint,
);
// Vẽ kim giây
final secondPaint = Paint()
..color = Colors.red // Màu của kim giây
..style = PaintingStyle.stroke // Kiểu vẽ là nét kẻ
..strokeCap = StrokeCap.round // Kiểu đầu của kim giây
..strokeWidth = 5; // Độ dày của kim giây
final secondAngle = (time.second - 15) * 6 * (pi / 180); // Tính
góc của kim giây
canvas.drawLine(
center,
center +
Offset(
cos(secondAngle) * radius * 0.9, sin(secondAngle) *
radius * 0.9),
secondPaint,
);
17
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return true;
}
}
18
Bài 4: Chương trình quản lý kho sử dụng
QR/BARCODE
Code
import 'package:flutter/material.dart'; // Import thư viện flutter
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
// Import thư viện flutter_barcode_scanner
void main() {
runApp(MyApp()); // Khởi chạy ứng dụng MyApp
}
19
// Hàm quét mã QR
Future<void> scanQRCode() async {
try {
final qrCode = await FlutterBarcodeScanner.scanBarcode(
"#ff6666", "Cancel", true, ScanMode.QR); // Quét mã QR
if (!mounted) return;
int temp = 0;
for (var product in products) {
if (product.ma == qrCode) {
temp = 1;
if (isNhapsPressed) {
product.quantity += 1;
product.time = DateTime.now();
}
if (isXuatsPressed) {
product.quantity -= 1;
product.time = DateTime.now();
}
}
}
if (qrCode == 'LK_04697') {
setState(() {
// Tìm sản phẩm bút trong danh sách và tăng số lượng lên 1
int index = products.indexWhere((product) => product.name ==
"Bút");
if (index != -1) {
// Tăng số lượng sản phẩm bút lên 1
if (isNhapsPressed) {
products[0].quantity += 0;
products[0].time = DateTime.now();
}
if (isXuatsPressed) {
products[0].quantity -= 0;
products[0].time = DateTime.now();
}
} else {
// Nếu không tìm thấy sản phẩm bút, có thể thêm mới hoặc
bỏ qua
// Ví dụ: thêm sản phẩm bút mới với số lượng 1 nếu chưa có
products.add(
Product(name: "Bút", quantity: 1, price: 5000, ma:
'LK_04697', time: DateTime.utc(2024, 3, 3)));
}
});
20
} else if (qrCode == '8934588063053') {
setState(() {
// Tìm sản phẩm bút trong danh sách và tăng số lượng lên 1
int index =
products.indexWhere((product) => product.name == "Chai
Nước");
if (index != -1) {
// Tăng số lượng sản phẩm bút lên 1
products[1].quantity += 0;
} else {
// Nếu không tìm thấy sản phẩm bút, có thể thêm mới hoặc
bỏ qua
// Ví dụ: thêm sản phẩm bút mới với số lượng 1 nếu chưa có
products.add(Product(
name: "Bút", quantity: 1, price: 5000, ma:
'8934588063053', time: DateTime.utc(2024, 3, 3)));
}
});
} else {
if(temp == 0){
_showAddProductDialog(qrCode); // Hiển thị hộp thoại thêm
sản phẩm mới
}
setState(() {});
}
} catch (e) {
// Xử lý lỗi
}
}
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Thêm Sản Phẩm Mới"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: nameController,
21
decoration: InputDecoration(labelText: "Tên Sản
Phẩm"),
),
TextField(
controller: priceController,
decoration: InputDecoration(labelText: "Giá Tiền"),
keyboardType: TextInputType.number,
),
],
),
actions: <Widget>[
TextButton(
child: Text("Thêm"),
onPressed: () {
setState(() {
products.add(Product(
name: nameController.text,
quantity: 1,
price: int.tryParse(priceController.text) ?? 0,
ma: qrCode,
time: DateTime.now()));
});
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 242, 206, 236), // Màu nền
của ứng dụng
appBar: AppBar(
title: Text('Mai Đông Thức - Mã Quang Lộc'), // Tiêu đề của
ứng dụng
backgroundColor: Color.fromARGB(173, 216, 230, 0), // Màu nền
của thanh tiêu đề
22
),
body: Container(
margin: EdgeInsets.all(10), // Thêm margin xung quanh bảng
padding: EdgeInsets.all(10), // Thêm padding bên trong khung
decoration: BoxDecoration(
color: Color.fromARGB(255, 184, 175, 175), // Màu nền của
khung
borderRadius: BorderRadius.circular(10), // Bo góc cho khung
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5), // Màu bóng
spreadRadius: 5, // Độ rộng bóng
blurRadius: 7, // Độ mờ bóng
offset: Offset(0, 3), // Vị trí bóng
),
],
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
headingRowColor:
MaterialStateProperty.all(Color.fromARGB(255, 232, 162, 96)), // Màu
dòng tiêu đề
dataRowColor:
MaterialStateProperty.all(Color.fromARGB(255, 166, 227, 255),), // Màu
dòng dữ liệu
columns: [
DataColumn(label: Text('Tên')), // Cột Tên sản phẩm
DataColumn(label: Text('SL')), // Cột Số lượng
DataColumn(label: Text('Giá Thành')), // Cột Giá thành
DataColumn(label: Text('Mã Sản Phẩm')), // Cột Mã sản
phẩm
DataColumn(label: Text('Thời Gian')), // Cột Thời gian
],
rows: products
.map((product) => DataRow(cells: [
DataCell(Text(product.name)), // Ô dữ liệu Tên
sản phẩm
DataCell(Text('${product.quantity}')), // Ô dữ
liệu Số lượng
DataCell(Text('${product.price} VND')), // Ô dữ
liệu Giá thành
DataCell(Text('${product.ma}')), // Ô dữ liệu Mã
sản phẩm
23
DataCell(Text('$
{_formattedDateTime(product.time)}')), // Ô dữ liệu Thời gian
]))
.toList(),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => scanQRCode(), // Xử lý sự kiện nhấn nút quét
mã QR
child: Icon(Icons.camera_alt), // Icon của nút
),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerDocked,
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(), // Hình dạng của thanh dưới
notchMargin: 6.0, // Khoảng cách từ mép đến lỗ
color: const Color.fromARGB(250, 216, 230, 0), // Màu nền của
thanh dưới
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(Icons.download,
color: isNhapsPressed ? Colors.red : Colors.blue),
// Icon nút Nhập hàng
onPressed: () {
setState(() {
isNhapsPressed = true; // Đặt trạng thái nút Nhập
hàng
isXuatsPressed = false; // Đặt trạng thái nút Xuất
hàng
// Logic cho hành động nhập hàng
});
},
),
IconButton(
icon: Icon(Icons.upload,
color: isXuatsPressed ? Colors.red : Colors.blue),
// Icon nút Xuất hàng
onPressed: () {
setState(() {
isXuatsPressed = true; // Đặt trạng thái nút Xuất
hàng
24
isNhapsPressed = false; // Đặt trạng thái nút Nhập
hàng
// Logic cho hành động xuất hàng
});
},
),
],
),
),
);
}
}
Product(
{required this.name,
required this.quantity,
required this.price,
required this.ma,
required this.time});
}
25