Compare commits

..

10 Commits

Author SHA1 Message Date
Misaka
7853c5ce59 chore: remove obsolete widget test
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:59:22 +08:00
Misaka
50fc548a48 feat: add INTERNET permission and scanner library
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:58:50 +08:00
Misaka
ffdccbca5e feat: wire up main.dart with ScanPage
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:58:11 +08:00
Misaka
54103a4f96 feat: add scan page with record list and send logic
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:57:57 +08:00
Misaka
c3b8ce02a2 feat: add settings page for URL configuration
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:57:28 +08:00
Misaka
d6bb5afb3c feat: add BroadcastReceiver and EventChannel for scanner
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:55:47 +08:00
Misaka
960d92e51f feat: add ScannerService with EventChannel
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:55:29 +08:00
Misaka
ef4dd51fc1 feat: add ApiService for HTTP POST
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:54:22 +08:00
Misaka
2693c13133 feat: add ScanRecord model with toJson
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:53:48 +08:00
Misaka
366e56710c feat: add http and shared_preferences dependencies
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 19:53:03 +08:00
13 changed files with 584 additions and 140 deletions

View File

@@ -1,8 +1,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:label="pad_scanner"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<uses-library android:name="android.scanner.library"/>
<activity
android:name=".MainActivity"
android:exported="true"

View File

@@ -1,5 +1,45 @@
package com.example.pad_scanner
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugin.common.EventChannel
class MainActivity : FlutterActivity()
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: io.flutter.embedding.engine.FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
EventChannel(flutterEngine.dartExecutor.binaryMessenger,
"com.example.pad_scanner/scan")
.setStreamHandler(object : EventChannel.StreamHandler {
private var receiver: BroadcastReceiver? = null
override fun onListen(arguments: Any?, events: io.flutter.plugin.common.EventChannel.EventSink?) {
if (events == null) return
receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val barcode = intent.getStringExtra("scannerdata") ?: return
events.success(mapOf(
"barcode" to barcode,
"codeType" to "UNKNOWN"
))
}
}
val filter = IntentFilter("com.android.server.scannerservice.broadcast")
registerReceiver(receiver, filter)
}
override fun onCancel(arguments: Any?) {
receiver?.let {
unregisterReceiver(it)
receiver = null
}
}
})
}
}

View File

@@ -1,122 +1,22 @@
import 'package:flutter/material.dart';
import 'package:pad_scanner/pages/scan_page.dart';
void main() {
runApp(const MyApp());
runApp(const PadScannerApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
class PadScannerApp extends StatelessWidget {
const PadScannerApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
title: 'PAD Scanner',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
home: const ScanPage(),
);
}
}

View File

@@ -0,0 +1,21 @@
enum SendStatus { pending, success, failed }
class ScanRecord {
final String barcode;
final String codeType;
final DateTime timestamp;
SendStatus status;
ScanRecord({
required this.barcode,
required this.codeType,
required this.timestamp,
this.status = SendStatus.pending,
});
Map<String, dynamic> toJson() => {
'barcode': barcode,
'code_type': codeType,
'timestamp': timestamp.toUtc().toIso8601String(),
};
}

127
lib/pages/scan_page.dart Normal file
View File

@@ -0,0 +1,127 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pad_scanner/models/scan_record.dart';
import 'package:pad_scanner/services/scanner_service.dart';
import 'package:pad_scanner/services/api_service.dart';
import 'package:pad_scanner/pages/settings_page.dart';
class ScanPage extends StatefulWidget {
const ScanPage({super.key});
@override
State<ScanPage> createState() => _ScanPageState();
}
class _ScanPageState extends State<ScanPage> {
final _scannerService = ScannerService();
final _apiService = ApiService();
final _records = <ScanRecord>[];
String _status = 'Waiting for scan...';
@override
void initState() {
super.initState();
_startListening();
}
void _startListening() {
_scannerService.scanResults.listen((result) async {
final record = ScanRecord(
barcode: result.barcode,
codeType: result.codeType,
timestamp: DateTime.now(),
);
setState(() {
_records.insert(0, record);
_status = 'Sending...';
});
final prefs = await SharedPreferences.getInstance();
final url = prefs.getString('api_url') ?? '';
if (url.isEmpty) {
setState(() {
record.status = SendStatus.failed;
_status = 'No URL configured. Go to Settings.';
});
return;
}
final ok = await _apiService.sendScanData(
url,
barcode: record.barcode,
codeType: record.codeType,
);
if (mounted) {
setState(() {
record.status = ok ? SendStatus.success : SendStatus.failed;
_status = ok ? 'Sent successfully' : 'Send failed';
});
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('PAD Scanner'),
actions: [
IconButton(
icon: const Icon(Icons.settings),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(builder: (_) => const SettingsPage()),
),
),
],
),
body: Column(
children: [
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Text(
_status,
style: Theme.of(context).textTheme.titleMedium,
textAlign: TextAlign.center,
),
),
Expanded(
child: _records.isEmpty
? const Center(
child: Text(
'No scans yet.\nPress the scan button on the device.',
textAlign: TextAlign.center))
: ListView.builder(
itemCount: _records.length,
itemBuilder: (context, index) {
final r = _records[index];
return ListTile(
title: Text(r.barcode),
subtitle: Text(
'${r.codeType} ${r.timestamp.toLocal().toIso8601String().substring(0, 19)}'),
trailing: Icon(
r.status == SendStatus.success
? Icons.check_circle
: r.status == SendStatus.failed
? Icons.error
: Icons.hourglass_empty,
color: r.status == SendStatus.success
? Colors.green
: r.status == SendStatus.failed
? Colors.red
: Colors.orange,
),
);
},
),
),
],
),
);
}
}

View File

@@ -0,0 +1,104 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pad_scanner/services/api_service.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
final _controller = TextEditingController();
final _apiService = ApiService();
bool _saving = false;
@override
void initState() {
super.initState();
_loadUrl();
}
Future<void> _loadUrl() async {
final prefs = await SharedPreferences.getInstance();
_controller.text = prefs.getString('api_url') ?? '';
}
Future<void> _saveUrl() async {
setState(() => _saving = true);
final prefs = await SharedPreferences.getInstance();
await prefs.setString('api_url', _controller.text.trim());
setState(() => _saving = false);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('URL saved')),
);
}
}
Future<void> _testConnection() async {
final url = _controller.text.trim();
if (url.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Please enter a URL first')),
);
return;
}
final ok = await _apiService.sendScanData(
url,
barcode: 'TEST_BARCODE',
codeType: 'TEST',
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(ok ? 'Connection OK' : 'Connection failed')),
);
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'API URL',
hintText: 'http://192.168.1.100:8000/scan',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.url,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _saving ? null : _saveUrl,
child: _saving
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2))
: const Text('Save'),
),
const SizedBox(height: 8),
OutlinedButton(
onPressed: _testConnection,
child: const Text('Test Connection'),
),
],
),
),
);
}
}

View File

@@ -0,0 +1,31 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
final http.Client _client;
ApiService({http.Client? client}) : _client = client ?? http.Client();
Future<bool> sendScanData(
String url, {
required String barcode,
required String codeType,
}) async {
try {
final response = await _client
.post(
Uri.parse(url),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'barcode': barcode,
'code_type': codeType,
'timestamp': DateTime.now().toUtc().toIso8601String(),
}),
)
.timeout(const Duration(seconds: 5));
return response.statusCode >= 200 && response.statusCode < 300;
} catch (_) {
return false;
}
}
}

View File

@@ -0,0 +1,27 @@
import 'dart:async';
import 'package:flutter/services.dart';
class ScanResult {
final String barcode;
final String codeType;
ScanResult({required this.barcode, required this.codeType});
}
class ScannerService {
static const _eventChannel =
EventChannel('com.example.pad_scanner/scan');
Stream<ScanResult>? _scanStream;
Stream<ScanResult> get scanResults {
_scanStream ??= _eventChannel
.receiveBroadcastStream()
.map((event) => event as Map)
.map((event) => ScanResult(
barcode: event['barcode'] as String? ?? '',
codeType: event['codeType'] as String? ?? 'UNKNOWN',
));
return _scanStream!;
}
}

View File

@@ -57,6 +57,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.3.3"
ffi:
dependency: transitive
description:
name: ffi
sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
file:
dependency: transitive
description:
name: file
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
url: "https://pub.dev"
source: hosted
version: "7.0.1"
flutter:
dependency: "direct main"
description: flutter
@@ -75,6 +91,27 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
http:
dependency: "direct main"
description:
name: http
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.dev"
source: hosted
version: "1.6.0"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.1.2"
leak_tracker:
dependency: transitive
description:
@@ -139,6 +176,102 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
url: "https://pub.dev"
source: hosted
version: "2.2.1"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
url: "https://pub.dev"
source: hosted
version: "2.3.0"
platform:
dependency: transitive
description:
name: platform
sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
url: "https://pub.dev"
source: hosted
version: "3.1.6"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5"
url: "https://pub.dev"
source: hosted
version: "2.5.3"
shared_preferences_android:
dependency: transitive
description:
name: shared_preferences_android
sha256: bd14436108211b0d4ee5038689a56d4ae3620fd72fd6036e113bf1345bc74d9e
url: "https://pub.dev"
source: hosted
version: "2.4.13"
shared_preferences_foundation:
dependency: transitive
description:
name: shared_preferences_foundation
sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03"
url: "https://pub.dev"
source: hosted
version: "2.5.4"
shared_preferences_linux:
dependency: transitive
description:
name: shared_preferences_linux
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_platform_interface:
dependency: transitive
description:
name: shared_preferences_platform_interface
sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_web:
dependency: transitive
description:
name: shared_preferences_web
sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
url: "https://pub.dev"
source: hosted
version: "2.4.3"
shared_preferences_windows:
dependency: transitive
description:
name: shared_preferences_windows
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
sky_engine:
dependency: transitive
description: flutter
@@ -192,6 +325,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.7.4"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vector_math:
dependency: transitive
description:
@@ -208,6 +349,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "15.0.0"
web:
dependency: transitive
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
sdks:
dart: ">=3.8.1 <4.0.0"
flutter: ">=3.18.0-18.0.pre.54"
flutter: ">=3.29.0"

View File

@@ -34,6 +34,8 @@ dependencies:
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
http: ^1.2.0
shared_preferences: ^2.2.0
dev_dependencies:
flutter_test:

View File

@@ -0,0 +1,29 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pad_scanner/models/scan_record.dart';
void main() {
group('ScanRecord', () {
test('creates with correct defaults', () {
final record = ScanRecord(
barcode: '1234567890',
codeType: 'CODE128',
timestamp: DateTime.parse('2026-05-07T10:30:00Z'),
);
expect(record.barcode, '1234567890');
expect(record.codeType, 'CODE128');
expect(record.status, SendStatus.pending);
});
test('toJson produces correct map', () {
final record = ScanRecord(
barcode: 'ABC123',
codeType: 'QR',
timestamp: DateTime.parse('2026-05-07T10:30:00Z'),
);
final json = record.toJson();
expect(json['barcode'], 'ABC123');
expect(json['code_type'], 'QR');
expect(json['timestamp'], '2026-05-07T10:30:00.000Z');
});
});
}

View File

@@ -0,0 +1,34 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:pad_scanner/services/api_service.dart';
void main() {
group('ApiService', () {
test('sendScanData returns true on 200', () async {
final client = MockClient((request) async {
return http.Response('{"status":"ok"}', 200);
});
final service = ApiService(client: client);
final result = await service.sendScanData(
'http://localhost:8000/scan',
barcode: '123456',
codeType: 'CODE128',
);
expect(result, isTrue);
});
test('sendScanData returns false on error', () async {
final client = MockClient((request) async {
return http.Response('error', 500);
});
final service = ApiService(client: client);
final result = await service.sendScanData(
'http://localhost:8000/scan',
barcode: '123456',
codeType: 'CODE128',
);
expect(result, isFalse);
});
});
}

View File

@@ -1,30 +0,0 @@
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pad_scanner/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}