亲宝软件园·资讯

展开

Flutter扫二维码

GalenWu 人气:0

首先在pubspec.yaml中添加:

dependencies:
  qrscan: ^0.3.2
  event_bus: ^2.0.0

在androd清单文件中加入以下权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

<!--
   路径:E:\chen\android\app\src\main\AndroidManifest.xml
  -->
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:event_bus/event_bus.dart';

void main() {
  runApp(MyApp());
}

final eventBus = EventBus();

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("QRScan")),
      body: BodyContent(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: [HYButton(), HYText()],
    ));
  }
}

class HYButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: Text("扫一扫"),
      onPressed: scan,
    );
  }

  Future scan() async {
    String? cameraScanResult = await scanner.scan(); //通过扫码获取二维码中的数据
    final info = QRInfo("${cameraScanResult}");
    eventBus.fire(info);
    print(cameraScanResult); //在控制台打印
  }
}

class HYText extends StatefulWidget {
  @override
  _HYTextState createState() => _HYTextState();
}

class _HYTextState extends State<HYText> {
  String message = "Hello GalenWu";

  @override
  void initState() {
    super.initState();

    eventBus.on<QRInfo>().listen((data) {
      setState(() {
        message = "${data.qrcode}";
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      message,
      style: TextStyle(fontSize: 30),
    );
  }
}

class QRInfo {
  String? qrcode;
  QRInfo(this.qrcode);
}

加载全部内容

相关教程
猜你喜欢
用户评论