Skip to content

Commit

Permalink
qrexample (xvrh#22)
Browse files Browse the repository at this point in the history
Porting over Flutter Web Chrome Extension
[example](https://github.com/jarrodcolburn/chromeapi/tree/main/example)
from discontinued [`chromeapi`
package](https://pub.dev/packages/chromeapi/example).

---------

Co-authored-by: Jarrod Colburn <jarrod@jarrodcolburn.com>
Co-authored-by: Xavier Hainaux <xavier.hainaux@gmail.com>
  • Loading branch information
3 people authored Mar 20, 2024
1 parent 37a1b93 commit 230c4d3
Show file tree
Hide file tree
Showing 20 changed files with 723 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ jobs:
- run: |
(dart pub get) && \
(cd extension_examples/dart && dart pub get) && \
(cd extension_examples/flutter && flutter pub get)
(cd extension_examples/flutter && flutter pub get) && \
(cd extension_examples/flutter2 && flutter pub get)
- run: flutter analyze --fatal-infos .
- run: dart run puppeteer:download_chrome
- run: xvfb-run --auto-servernum dart test
Expand Down
21 changes: 21 additions & 0 deletions extension_examples/flutter2/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Souvik Biswas

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
27 changes: 27 additions & 0 deletions extension_examples/flutter2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Flutter QR - Current tab URL - Chrome extension

## Calls `chrome.tabs.query` to generate the QR Code using the URL of the current Chrome tab.

![Chrome extension in action](screenshots/qr-code-url-ext-demo.gif)

## Usage

To use this project as a Chrome extension, follow the steps below:

1. From the project directory, run:

```sh
flutter build web --web-renderer html --csp
```

2. Go to the following URL from Chrome browser:

```url
chrome://extensions
```

3. Enable the **Developer mode**.

4. Click **Load unpacked**. Select the `<project_dir>/build/web` folder.

This will install the extension to your Chrome browser and then you will be able to access the extension by clicking on the **extension icon**.
30 changes: 30 additions & 0 deletions extension_examples/flutter2/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.

# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml

linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at
# https://dart-lang.github.io/linter/lints/index.html.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options

17 changes: 17 additions & 0 deletions extension_examples/flutter2/lib/color_list.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import 'package:flutter/material.dart';

const List<Color> qrBackgroundColors = [
Colors.white,
Colors.orange,
Colors.blueGrey,
Colors.red,
Colors.greenAccent,
];

const List<Color> qrColors = [
Colors.black,
Colors.purple,
Colors.white,
Colors.green,
Colors.blue,
];
82 changes: 82 additions & 0 deletions extension_examples/flutter2/lib/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import 'package:chrome_extension/tabs.dart';
import 'package:flutter/material.dart' hide Tab;
import 'package:web/web.dart' as web;
import 'qr_view.dart';

void main() => runApp(const MyApp());

Future<Tab> getActiveTab() async {
List<Tab> tabs =
await chrome.tabs.query(QueryInfo(active: true, currentWindow: true));
return tabs.first;
}

void sizePopUp({int? heightPx, int? widthPx}) {
String size = '';
if (heightPx case int height) size += 'height: ${height}px;';
if (widthPx case int width) size += 'width: ${width}px;';
if (size.isEmpty) return;
final styleTag = web.document.createElement('style');
styleTag.textContent = 'html { $size }';
web.document.head?.append(styleTag);
}

final Map<String, Widget Function(BuildContext)> routes = {
'options': (_) {
sizePopUp(heightPx: 400, widthPx: 400);
return buildOptionsPage(_);
},
'popup': (_) {
sizePopUp(heightPx: 350, widthPx: 650);
return FutureBuilder<Tab>(
future: getActiveTab(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return QRView(qrText: snapshot.data!.url!);
} else {
return const Center(child: CircularProgressIndicator());
}
},
);
}
};

Widget buildOptionsPage(BuildContext context) {
return Scaffold(
backgroundColor: Colors.red,
appBar: AppBar(
title: const Text('Options'),
),
body: const Center(
child: Text('Options page'),
),
);
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
routes: routes,
title: 'Flutter Chrome Extension',
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue),
home: FutureBuilder<String?>(
future: getActiveTab().then((tab) => tab.url),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
if (snapshot.data case String url) {
return QRView(qrText: url);
}
throw Exception('Error: Could not obtain url. ${snapshot.error}');
default:
return const Center(child: CircularProgressIndicator());
}
},
),
);
}
}
192 changes: 192 additions & 0 deletions extension_examples/flutter2/lib/qr_view.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import 'package:flutter/material.dart' hide Tab;
import 'package:qr_flutter/qr_flutter.dart';
import 'color_list.dart';

class QRView extends StatefulWidget {
final String? qrText;
final bool enabled;
const QRView({Key? key, this.qrText, this.enabled = false}) : super(key: key);

@override
State<QRView> createState() => _QRViewState();
}

class _QRViewState extends State<QRView> {
late final TextEditingController _textController;
late final FocusNode _textFocus;
bool _enabled = false;
String qrText = '';
int qrColorIndex = 0;
int qrBackgroundColorIndex = 0;

@override
void initState() {
setState(() {
_enabled = widget.enabled;
qrText = widget.qrText ?? '';
_textController = TextEditingController(text: qrText);
_textFocus = FocusNode();
});
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 24.0,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(16),
child: QrImageView(
data: qrText,
padding: const EdgeInsets.all(16),
dataModuleStyle:
QrDataModuleStyle(color: qrColors[qrColorIndex]),
eyeStyle: QrEyeStyle(color: qrColors[qrColorIndex]),
backgroundColor: qrBackgroundColors[qrBackgroundColorIndex],
version: QrVersions.auto,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 24.0,
vertical: 16,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
TextField(
enabled: _enabled,
controller: _textController,
focusNode: _textFocus,
decoration: InputDecoration(
labelText: 'QR Text',
labelStyle: const TextStyle(
color: Color(0xFF80919F),
),
hintText: 'Enter text / URL',
hintStyle: const TextStyle(
color: Color(0xFF80919F),
),
enabledBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.black54,
width: 2,
),
borderRadius: BorderRadius.circular(16),
),
focusedBorder: OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.black,
width: 2,
),
borderRadius: BorderRadius.circular(16),
),
),
onChanged: (value) => setState(() {
qrText = value;
}),
),
const SizedBox(height: 24),
const Text(
'Choose QR Color',
style: TextStyle(
color: Colors.black,
fontSize: 16,
),
),
Expanded(
child: ListView.separated(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
separatorBuilder: (_, __) => const SizedBox(width: 8),
itemCount: qrColors.length,
itemBuilder: (context, index) {
return InkWell(
hoverColor: Colors.transparent,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
onTap: () => setState(() {
qrColorIndex = index;
}),
child: Stack(
alignment: Alignment.center,
children: [
CircleAvatar(
radius: qrColorIndex == index ? 23 : 22,
backgroundColor: qrColorIndex == index
? Colors.black
: Colors.black26,
),
CircleAvatar(
radius: 20,
backgroundColor: qrColors[index],
),
],
),
);
},
),
),
const Text(
'Choose QR Background Color',
style: TextStyle(
color: Colors.black,
fontSize: 16,
),
),
Expanded(
child: ListView.separated(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
separatorBuilder: (_, __) => const SizedBox(width: 8),
itemCount: qrBackgroundColors.length,
itemBuilder: (context, index) {
return InkWell(
hoverColor: Colors.transparent,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
onTap: () => setState(() {
qrBackgroundColorIndex = index;
}),
child: Stack(
alignment: Alignment.center,
children: [
CircleAvatar(
radius:
qrBackgroundColorIndex == index ? 23 : 22,
backgroundColor:
qrBackgroundColorIndex == index
? Colors.black
: Colors.black26,
),
CircleAvatar(
radius: 20,
backgroundColor: qrBackgroundColors[index],
),
],
),
);
},
),
),
const SizedBox(height: 16),
],
),
),
)
],
),
),
);
}
}
Loading

0 comments on commit 230c4d3

Please sign in to comment.