You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter Android中用Firebase Firestore数据生成二维码?

问题:无法从Firebase Firestore获取数据生成二维码

我有一段从网上获取的二维码生成代码,它仅支持接收字符串数据。我已尝试对其进行修改,能够展示列表,但无法从Firebase Firestore中获取数据。这段代码可以生成二维码,但无法使用来自Firestore的映射数据。我期望它能展示当前用户在Firestore数据库中的字段和键值。

原代码:

import 'dart:convert';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:myadnumobile/read%20data/get_user_data.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'dart:ui';
import 'package:flutter/rendering.dart';

class qrScanPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _qrScanPageState();
}

class _qrScanPageState extends State<qrScanPage> {
  
  String qrData =
      "test";
        // already generated qr code when the page opens

String _buildQrCode() { 
  var content = 's';
  var type;
  var email;
  var mac;
  Map<String,dynamic> myData = {
    'type': type,
    'content': content,
    'email': email,
    'mac': mac,
  };

  String encodedJson = jsonEncode(myData);
  print(encodedJson);
  return encodedJson;
}

  @override
  Widget build(BuildContext context) {
  final user = FirebaseAuth.instance.currentUser!;
  final uid = user.uid;
    var endcodedJson = _buildQrCode();
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      child: Scaffold(
        backgroundColor: Color.fromARGB(31, 146, 144, 144),
        appBar: AppBar(
          title: Text('QR Code Generator'),
          actions: <Widget>[],
          backgroundColor: Color.fromARGB(31, 146, 144, 144),
        ),
        body: SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.all(20.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                QrImage(
                  //plce where the QR Image will be shown
                  data: endcodedJson,
                  backgroundColor: Colors.white,
                ),
                SizedBox(
                  height: 40.0,
                ),
                Text(
                  "New QR Link Generator",
                  style: TextStyle(fontSize: 20.0, color: Colors.white),
                ),
                TextField(
                  controller: qrdataFeed,
                  style: TextStyle(color: Colors.white),
                  decoration: InputDecoration(
                    enabledBorder: UnderlineInputBorder(      
                          borderSide: BorderSide(color: Colors.white),   
                          ),  
                  focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.white),
                       ),  
                    hintText: "Input your data",
                    hintStyle: TextStyle(color: Colors.white)
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(40, 20, 40, 0),
                  child: ElevatedButton(
                    child: Text('Generate QR',
                            style: TextStyle(
                              color: Colors.black,
                              ),
                            ),
                    onPressed: _buildQrCode,
                    style: ElevatedButton.styleFrom(
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(15),
                                ),
                                primary: Colors.white,
                                padding: EdgeInsets.symmetric(horizontal: 70, vertical: 12), //padding for the button
                                textStyle: TextStyle(
                                  fontSize: 18,
                                  )
                            ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  final qrdataFeed = TextEditingController();
}

解决方案

1. 添加状态变量存储用户数据

在_qrScanPageState类中添加变量,用于保存从Firestore获取的用户数据和加载状态:

Map<String, dynamic>? userData;
bool isLoading = true;

2. 初始化时获取Firestore数据

重写initState方法,在页面初始化时获取当前用户的Firestore数据:

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

Future<void> _fetchUserData() async {
  final user = FirebaseAuth.instance.currentUser!;
  // 替换成你的Firestore集合名称,这里假设是"users"
  final docSnapshot = await FirebaseFirestore.instance.collection('users').doc(user.uid).get();
  
  setState(() {
    if (docSnapshot.exists) {
      userData = docSnapshot.data();
    }
    isLoading = false;
  });

  if (!docSnapshot.exists) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('未找到用户数据')),
    );
  }
}

3. 修改二维码生成逻辑

更新_buildQrCode方法,使用从Firestore获取的真实用户数据:

String _buildQrCode() { 
  if (userData == null) {
    return jsonEncode({'error': '用户数据未加载'});
  }

  // 按需选择需要放入二维码的字段,或直接使用整个userData
  Map<String,dynamic> qrContent = {
    'type': 'user_profile',
    'content': '用户信息',
    'email': userData!['email'],
    'mac': userData!['mac'],
    // 可添加其他需要的字段,比如userData!['username']等
  };

  String encodedJson = jsonEncode(qrContent);
  print(encodedJson);
  return encodedJson;
}

4. 处理加载状态

在build方法中先判断数据是否加载完成,避免生成空二维码:

@override
Widget build(BuildContext context) {
  if (isLoading) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(31, 146, 144, 144),
      appBar: AppBar(
        title: const Text('QR Code Generator'),
        backgroundColor: const Color.fromARGB(31, 146, 144, 144),
      ),
      body: const Center(child: CircularProgressIndicator(color: Colors.white)),
    );
  }

  final encodedJson = _buildQrCode();
  // 保留原build方法的剩余代码...
}

5. 修复按钮点击逻辑

原按钮点击仅调用_buildQrCode但不会更新UI,修改为触发状态刷新:

onPressed: () {
  setState(() {});
},

如果需要点击按钮时重新获取最新数据,可改为:

onPressed: () async {
  await _fetchUserData();
  setState(() {});
},

内容的提问来源于stack exchange,提问作者Polly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:20:49