📜  Flutter – 二维码扫描器和二维码生成器

📅  最后修改于: 2021-09-23 06:28:52             🧑  作者: Mango

如今,使用二维码访问网站、图像和文件已被广泛使用。这些二维码用于支付,易于使用。您可以在 Google Pay、Amazon Pay 等各种支付应用程序中看到此功能。在今天的文章中,我们将看到如何在flutter应用程序中为某些链接和二维码扫描仪生成二维码。

按照以下步骤在Flutter构建一个简单的 QR 扫描仪和生成器应用程序:

第 1 步:首先在您的 pubspec.yaml 文件中添加以下依赖项

Dart
dependencies:
    
  path_provider: ^1.6.24
  qr_flutter: ^3.2.0
  barcode_scan_fix: ^1.0.2


Dart
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //Given Title
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      //Given Theme Color
      theme: ThemeData(
       primarySwatch: Colors.indigo,
      ),
      //Declared first page of our app
      home: HomePage(),
    );
  }
}


Dart
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State {
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      
      body: Container(
        width: 500,
        height: 500,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            //Display Image
            Image(image: NetworkImage("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQyYwscUPOH_qPPe8Hp0HAbFNMx-TxRFubpg&usqp=CAU")),
              
            //First Button
            FlatButton(
              padding: EdgeInsets.all(15),
              onPressed: (){
                Navigator.of(context).push(MaterialPageRoute(builder: (context)=> ScanQR()));
              },
                child: Text("Scan QR Code",style: TextStyle(color: Colors.indigo[900]),),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(color: Colors.indigo[900]),
              ),
            ),
            SizedBox(height: 10),
  
            //Second Button
            FlatButton(
              padding: EdgeInsets.all(15),
              onPressed: (){
                Navigator.of(context).push(MaterialPageRoute(builder: (context)=>
                                                             GenerateQR()));
              },
              child: Text("Generate QR Code", style: TextStyle(color: Colors.indigo[900]),),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(color: Colors.indigo[900]),
              ),
            ),
          ],
        ),
      )
    );
  }
}


Dart
import 'package:barcode_scan_fix/barcode_scan.dart';
import 'package:flutter/material.dart';
  
class ScanQR extends StatefulWidget {
  @override
  _ScanQRState createState() => _ScanQRState();
}
  
class _ScanQRState extends State {
  
  String qrCodeResult = "Not Yet Scanned";
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Scan QR Code"),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
    child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: [
      //Message displayed over here
      Text(
        "Result",
        style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold),
        textAlign: TextAlign.center,
      ),
      Text(
        qrCodeResult,
        style: TextStyle(
          fontSize: 20.0,
        ),
        textAlign: TextAlign.center,
      ),
      SizedBox(
        height: 20.0,
      ),
  
      //Button to scan QR code
      FlatButton(
        padding: EdgeInsets.all(15),
        onPressed: () async {
          String codeSanner = await BarcodeScanner.scan();    //barcode scnner
          setState(() {
            qrCodeResult = codeSanner;
          });
        },
        child: Text("Open Scanner",style: TextStyle(color: Colors.indigo[900]),),
        //Button having rounded rectangle border
        shape: RoundedRectangleBorder(
          side: BorderSide(color: Colors.indigo[900]),
          borderRadius: BorderRadius.circular(20.0),
        ),
      ),
  
         ],
        ),
      ),
    );
  }
}


Dart
import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
  
class GenerateQR extends StatefulWidget {
  @override
  _GenerateQRState createState() => _GenerateQRState();
}
  
class _GenerateQRState extends State {
  
  String qrData="https://github.com/ChinmayMunje";
  final qrdataFeed = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //Appbar having title
      appBar: AppBar(
        title: Center(child: Text("Generate QR Code")),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
            
          //Scroll view given to Column
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              QrImage(data: qrData),
              SizedBox(height: 20),
              Text("Generate QR Code",style: TextStyle(fontSize: 20),),
                
              //TextField for input link
              TextField(
                decoration: InputDecoration(
                  hintText: "Enter your link here..."
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                //Button for generating QR code
                child: FlatButton(
                    onPressed: () async {
                      //a little validation for the textfield
                      if (qrdataFeed.text.isEmpty) {        
                        setState(() {
                          qrData = "";
                        });
                      } else {
                        setState(() {
                          qrData = qrdataFeed.text;
                        });
                      }
                    },
                  //Title given on Button
                    child: Text("Generate QR Code",style: TextStyle(color: Colors.indigo[900],),),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                    side: BorderSide(color: Colors.indigo[900]),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


现在点击pub.get进行配置。

第 2 步:现在导航到 main。 dart() 文件并返回 Material App()

首先,我们在 main函数的runApp中声明了MyApp() 。然后我们为MyApp创建了 StatelessWidget,其中我们返回了MaterialApp()。在这个MaterialApp() 中,我们给出了我们的应用程序的标题,然后将我们的应用程序的主题声明为primarySwatch as indigo。然后我们在主页中给出了我们的第一个屏幕或滑块应用程序: HomePage()

Dart

void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //Given Title
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      //Given Theme Color
      theme: ThemeData(
       primarySwatch: Colors.indigo,
      ),
      //Declared first page of our app
      home: HomePage(),
    );
  }
}

第 3 步:为 HomePage 声明 StatefulWidget()

StatefulWidget() 中返回Scaffold()小部件。在主体部分的 Scaffold() Widget 中,我们已经声明了 Container() 具有宽度和高度。在那个 Container() 中,我们给出了 Column,其中我们将mainAxisAlignment作为中心,将CrossAxisAlignment作为拉伸。之后,我们在该图像下方给出了一个图像作为网络图像,我们给出了具有颜色、边界半径和边界边的圆形 FlatButton()。在那个FlatButton 上,我们提供了onPressed方法,用于导航到下一个屏幕ScanQR()。

下面我们给出了另一个具有颜色、边框半径和边框边的圆形FlatButton() 。在那个FlatButton 上,我们提供了onPressed方法,用于导航到下一个屏幕GenerateQR()

Dart

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State {
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      
      body: Container(
        width: 500,
        height: 500,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            //Display Image
            Image(image: NetworkImage("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQyYwscUPOH_qPPe8Hp0HAbFNMx-TxRFubpg&usqp=CAU")),
              
            //First Button
            FlatButton(
              padding: EdgeInsets.all(15),
              onPressed: (){
                Navigator.of(context).push(MaterialPageRoute(builder: (context)=> ScanQR()));
              },
                child: Text("Scan QR Code",style: TextStyle(color: Colors.indigo[900]),),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(color: Colors.indigo[900]),
              ),
            ),
            SizedBox(height: 10),
  
            //Second Button
            FlatButton(
              padding: EdgeInsets.all(15),
              onPressed: (){
                Navigator.of(context).push(MaterialPageRoute(builder: (context)=>
                                                             GenerateQR()));
              },
              child: Text("Generate QR Code", style: TextStyle(color: Colors.indigo[900]),),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(color: Colors.indigo[900]),
              ),
            ),
          ],
        ),
      )
    );
  }
}

第 4 步:导航到 ScanQR() 页面。

首先在这个文件中,我们导入了包barcode_scan_fix 。然后,我们已经创造了StateFulWidgetScanQR。在那种状态下,我们将 String 声明为qrcoderesult = ‘Not yet Scanned’ 。之后在Scaffold() 中,我们用标题声明了Appbar 。在正文部分,我们已经声明了 Column() 用Container()包裹,并以mainAxisAlignment为中心,将CrossAxisAlignment作为拉伸。在那之后,我们已经声明了两个文本小部件,第一个文本小部件为给定的标题声明了。第二个文本小部件用于声明我们给出的字符串。之后,我们提供了一个FlatButton()并在其onPressed方法中,我们提供了codeScanner用于扫描我们从中导入的二维码 bar_code_scan_fix 库。

Dart

import 'package:barcode_scan_fix/barcode_scan.dart';
import 'package:flutter/material.dart';
  
class ScanQR extends StatefulWidget {
  @override
  _ScanQRState createState() => _ScanQRState();
}
  
class _ScanQRState extends State {
  
  String qrCodeResult = "Not Yet Scanned";
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Scan QR Code"),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
    child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: [
      //Message displayed over here
      Text(
        "Result",
        style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold),
        textAlign: TextAlign.center,
      ),
      Text(
        qrCodeResult,
        style: TextStyle(
          fontSize: 20.0,
        ),
        textAlign: TextAlign.center,
      ),
      SizedBox(
        height: 20.0,
      ),
  
      //Button to scan QR code
      FlatButton(
        padding: EdgeInsets.all(15),
        onPressed: () async {
          String codeSanner = await BarcodeScanner.scan();    //barcode scnner
          setState(() {
            qrCodeResult = codeSanner;
          });
        },
        child: Text("Open Scanner",style: TextStyle(color: Colors.indigo[900]),),
        //Button having rounded rectangle border
        shape: RoundedRectangleBorder(
          side: BorderSide(color: Colors.indigo[900]),
          borderRadius: BorderRadius.circular(20.0),
        ),
      ),
  
         ],
        ),
      ),
    );
  }
}

第 5 步:导航到 GenerateQr() 页面。

首先,我们为GenerateQr()类提供了StateFulWidget() 。在这里,我们将最终变量指定为TextEditingController()。Scaffold()部分,我们提供了appbar和标题。在正文部分,我们给出了Container()具有以mainAxisAlignment为中心和CrossAxisAlignment作为拉伸的Column() 。用SingleChildScrollView()包裹之后,我们提供了TextField()用于提供输入链接以转换为条形码。之后,我们提供了 FlatButton() ,它将我们的链接转换为二维码。在这个FlatButton () 的onPressed中我们已经声明了它的逻辑,其中使用导入的库qr_link将链接转换为二维码。

Dart

import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
  
class GenerateQR extends StatefulWidget {
  @override
  _GenerateQRState createState() => _GenerateQRState();
}
  
class _GenerateQRState extends State {
  
  String qrData="https://github.com/ChinmayMunje";
  final qrdataFeed = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //Appbar having title
      appBar: AppBar(
        title: Center(child: Text("Generate QR Code")),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
            
          //Scroll view given to Column
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              QrImage(data: qrData),
              SizedBox(height: 20),
              Text("Generate QR Code",style: TextStyle(fontSize: 20),),
                
              //TextField for input link
              TextField(
                decoration: InputDecoration(
                  hintText: "Enter your link here..."
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                //Button for generating QR code
                child: FlatButton(
                    onPressed: () async {
                      //a little validation for the textfield
                      if (qrdataFeed.text.isEmpty) {        
                        setState(() {
                          qrData = "";
                        });
                      } else {
                        setState(() {
                          qrData = qrdataFeed.text;
                        });
                      }
                    },
                  //Title given on Button
                    child: Text("Generate QR Code",style: TextStyle(color: Colors.indigo[900],),),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                    side: BorderSide(color: Colors.indigo[900]),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

输出:

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!