DavBfr / dart_barcode

Barcode generation library
https://pub.dev/packages/barcode
Apache License 2.0
139 stars 39 forks source link

QrInputTooLongException: Input too long. 1324596 > 23648 The relevant error-causing widget was: BarcodeWidget #20

Closed azeemohd786 closed 4 years ago

azeemohd786 commented 4 years ago

I have an issue when I tried to call my barcode in data getting error

QrInputTooLongException: Input too long. 1324596 > 23648
The relevant error-causing widget was: 
  BarcodeWidget file:///Applications/iOS%20Projects/IVS/kash_app/lib/QRScene.dart:237:11

written code is,

 return BarcodeWidget(
       data: "$/93344<..>",
       barcode: Barcode.qrCode(),
   }

It doesnt show any qrcode in screen.

but I tried same data in https://davbfr.github.io/dart_barcode/#/ it works and shows the QR-code.

DavBfr commented 4 years ago

did you escape $ ?

azeemohd786 commented 4 years ago

@DavBfr

my string data is like /9j...iigAoo<…> I save the string by usingString _barcode;

used in code as,

return BarcodeWidget(
       data: "$_barcode",
       barcode: Barcode.qrCode(),
   }

if I tried to call the string directly without let constant it works..

DavBfr commented 4 years ago

Why not directly _barcode without the quotes?

DavBfr commented 4 years ago

can you provide a full main.dart that reproduces the issue?

azeemohd786 commented 4 years ago

@DavBfr

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kash_app/SecurityQuestions.dart';
import 'package:kash_app/BaseAlertDialog.dart';
import 'package:kash_app/CircleProgress.dart';
import 'dart:math' as math;

import 'package:dotted_border/dotted_border.dart';
import 'dart:ui';
import 'dart:async';

import 'package:http/http.dart' as http;
import 'package:http/io_client.dart';
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:kash_app/Models/KhRedemptionDetails.dart';
import 'package:barcode_widget/barcode_widget.dart';

//

import 'package:kash_app/Dashboard.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: QRScene()
    );
  }
}

class QRScene extends StatefulWidget {
 // QRScene({Key key, this.title}) : super(key: key);

//  final String title;

  var myKashHeroId;
  QRScene({
    this.myKashHeroId
  });

  @override
  _QRSceneState createState() => _QRSceneState();
}

class _QRSceneState extends State<QRScene>  with SingleTickerProviderStateMixin{
 // AnimationController progressController;
  Animation<double> animation;
 AnimationController controller;

  String _errorMessage;
  KhRedemptionDetails _khRedemptionDetails;

  //
  String _recipient;
  String _issuerName;
  String _barcode;
  String _redemptionCode;
  double _amount;
  String userName;

  bool _loading = false;

  String get timerString {
    Duration duration = controller.duration * controller.value;
    return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
  }

  //
  @override
  void initState() {
    showProgressView();
    postMethod();
    // TODO: implement initState
    super.initState();

    controller = AnimationController(vsync: this, duration: Duration(seconds: 600),);
    // progressController = AnimationController(vsync: this,duration: Duration(milliseconds: 1000));
    animation = Tween<double>(begin: 0,end: 100).animate(controller)..addListener((){
      setState(() {

      });
    });
    startTimer();
  }

  startTimer() {
    controller.reverse(
        from: controller.value == 0.0
            ? 1.0
            : controller.value);
  }
  timerProgressView() {
    return CustomPaint(
          foregroundPainter: CustomTimerPainter(animation: controller,
            backgroundColor: Colors.white,//
            color: Colors.redAccent,),
          child: Center(child: Text("${timerString.toLowerCase()}",style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),),)

    );
  }

  Widget get rectBorderWidget {
    return DottedBorder(
      color: '#D3D7D6'.toColor(),
      dashPattern: [8, 4],
      strokeWidth: 3,
      child: Container(
        height: 70,
        width: MediaQuery.of(context).size.width,
        color: Colors.white,
      ),
    );
  }

  postMethod() async {
    _loading = !_loading;
    var url = "https://stagingapi...";
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userName = prefs.getString('infoUsername');
    String _userId = prefs.getString('userId');
    String _apiToken = prefs.getString('token');

    int usrId;
    usrId = int.parse(_userId);
    int khId;
    khId = int.parse(widget.myKashHeroId.toString());

    final body = jsonEncode({ "customerID": 193,
      "kashHeroID": khId });

    var response = await http.post(url, headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer $_apiToken',
    }, body: body);
    print(response.body);
    print("${response.statusCode}");

    if (response.statusCode == 200){

      final Map<String, dynamic> responseString = jsonDecode(response.body);
      if (responseString['success'] == true) {
        print('here is true');
        _khRedemptionDetails = KhRedemptionDetails.fromJson(responseString);
        _recipient = _khRedemptionDetails.payload[0].recipient;
        _issuerName = _khRedemptionDetails.payload[0].issuerName;
        _barcode = _khRedemptionDetails.payload[0].barcode;
        _redemptionCode = _khRedemptionDetails.payload[0].redemptionCode;
        _amount = _khRedemptionDetails.payload[0].amount;
        print(_barcode);
        setState(() {
          getBarcodeWidget();
          getuserNameWidget();
          getRedemptionCodeWidget();
          getRecipientWidget();
          getIssuerWidget();
          getamountWidget();

          _loading = !_loading;

        });

      } else {
        print('here is false');
        _loading = !_loading;
        _errorMessage = (responseString[0]['errorMessgaes']);
        var baseDialog = OneButtonBaseAlertDialog(
            title: "$_errorMessage",
            content: "$_errorMessage: please try again",
            yesOnPressed: () {
              _loading = !_loading;
              Navigator.of(context, rootNavigator: true)
                  .pop();
            },
            yes: "OK");
        showDialog(context: context, builder: (BuildContext context) => baseDialog);
      }
    } else {
      _loading = !_loading;
      var baseDialog = OneButtonBaseAlertDialog(
          title: "Error",
          content: "Something went wrong, please try again later",
          yesOnPressed: () {
            _loading = !_loading;
            Navigator.of(context, rootNavigator: true)
                .pop();
          },
          yes: "OK");
      showDialog(context: context, builder: (BuildContext context) => baseDialog);

    }

  }

  getBarcodeWidget(){
   return BarcodeWidget(
       data: "$_barcode",
       barcode: Barcode.qrCode(),
   );
  }

  getuserNameWidget(){
    return Text('$userName',
      textAlign: TextAlign.left,
      style: TextStyle(fontFamily: 'Montserrat, Regular',
          color: '#E44D36'.toColor(), fontWeight: FontWeight.w500, fontSize: 18),);
  }

  getamountWidget(){

    return  Text("\$$_amount     ", textAlign: TextAlign.left,
      style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w700, color: Colors.white, fontSize: 15,),);

  }

  getRecipientWidget(){
    return TextSpan(text: '$_recipient',
      style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w500, color: '#E44D36'.toColor(), fontSize: 14,),);
  }
  getIssuerWidget(){
    return TextSpan(text: '$_issuerName',
      style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w500, color: '#E44D36'.toColor(), fontSize: 14,),);
    ;
  }
  getRedemptionCodeWidget(){
    return Text(
        '$_redemptionCode',
        textAlign: TextAlign.center,
        style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w700, color: '#E44D36'.toColor(), fontSize: 16,),);

  }

  showProgressView(){
    return _loading ? Container(
      child: Center(
        child: CircularProgressIndicator(backgroundColor: '#E44D36'.toColor(),),
      ),
    ) : Container();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 0,
        backgroundColor: '#053F4E'.toColor(),
      ),
      body: Padding(
      padding: EdgeInsets.all(0),
          child: ListView(
           children: <Widget>[
               new Container(
                 height: 75,
                color: Colors.white,
                child: CupertinoNavigationBar(
               actionsForegroundColor: Colors.deepOrange,
                backgroundColor: Colors.white,
                  middle: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image(
                    image: new AssetImage("assets/khIcon.png"),
                    color: '#E44D36'.toColor(),
                    width:  23.00,
                    height: 23.00,
                  ),
                     SizedBox(width: 4),
                      getuserNameWidget(),
                ]),
           ),
           ),
           //
                  new Container(
                    alignment: Alignment.center,
                    color: '#F5F5F6'.toColor(),
                    height: 720,
                    padding:  EdgeInsets.fromLTRB(20, 20, 20, 20),
                     child: Column(
                  //mainAxisAlignment: MainAxisAlignment.center,

                   children: [
                       new Container(
                         padding: EdgeInsets.only(top: 0, right: 0, left: 0),
                         height: 375,
                         child: getBarcodeWidget(),
                         // child: Image(
                         //   image: new AssetImage("assets/qrsample.png"),
                         //   color: null, fit: BoxFit.fill
                         // ),
                       ),
                         new Container(
                       padding: EdgeInsets.only(top: 10),
                       height: 50,
                            child: Text(
                         'REDEMPTION CODE',
                         textAlign: TextAlign.center,
                         style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w700, color: '#053F4E'.toColor(), fontSize: 14,),
                       ),
                     ),
                     // stack timer
                     new Stack(
                       alignment: Alignment.center,
                       children: <Widget>[
                         rectBorderWidget,
                         new Container(
                           height: 70.0,
                           width: MediaQuery.of(context).size.width,

                         child: new  Card(
                             color: Colors.white,
                             elevation: 4.0,
                             child: new Row(
                                 children: [
                                   new Container(
                                     alignment: Alignment.centerLeft,
                                     child: Text(
                                       '  EXPIRES IN',
                                       textAlign: TextAlign.center,
                                       style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w300, color: '#053F4E'.toColor(), fontSize: 14,),
                                     ),
                                   ),

                                 ])),),

                         new Container(
                           height: 72,
                           width: 72,
                           decoration: BoxDecoration(
                               border: Border.all(
                                 color: '#D3D7D6'.toColor(),width: 7,
                               ),
                               borderRadius: BorderRadius.all(Radius.circular(36))
                           ),
                           child: timerProgressView(),

                         ),

                         new Container(
                           padding: EdgeInsets.only(right: 15),
                           alignment: Alignment.centerRight,
                           child: getRedemptionCodeWidget(),
                         ),
                         showProgressView(),
                         // _loading ? Container(
                         //   child: Center(
                         //     child: CircularProgressIndicator(backgroundColor: '#E44D36'.toColor(),),
                         //   ),
                         // ) : Container()

                       ],

                     ),

                     new Container(
                       padding: EdgeInsets.only(top:10,),
                       height: 80.0,
                       width: MediaQuery.of(context).size.width,
                       child: new  Card(
                           color: Colors.white,
                           elevation: 4.0,
                           child: new Row(
                               children: [
                                 new Container(
                                   padding: EdgeInsets.only(left: 5),
                                   width: 220,
                                   height: 70,
                                   child: Column(
                                    children: [
                                      new Container(
                                        padding: EdgeInsets.only(top: 10),
                                        height: 30,
                                        alignment: Alignment.centerLeft,
                                          child: RichText(
                                            textAlign: TextAlign.left,
                                           text: TextSpan(
                                            text: 'Recipient : ',
                                             style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w500, color: '#053F4E'.toColor(), fontSize: 14,),
                                               children: <TextSpan>[
                                               getRecipientWidget(),
                                              ],
                                            ),
                                         )
                                      ),
                                      new Container(
                                        padding: EdgeInsets.only(top: 10),
                                        height: 30,
                                        alignment: Alignment.centerLeft,
                                          child: RichText(
                                            textAlign: TextAlign.left,
                                            text: TextSpan(
                                              text: 'From : ',
                                              style: TextStyle(fontFamily: 'Montserrat, Regular', fontWeight: FontWeight.w500, color: '#053F4E'.toColor(), fontSize: 14,),
                                              children: <TextSpan>[
                                               getIssuerWidget(),
                                              ],
                                            ),
                                          )
                                      ),

                                      ])

                                 ),
                                 new Container(
                                   alignment: Alignment.centerRight,
                                   width: 130,
                                   height: 70,
                                   child: MaterialButton(
                                     padding: EdgeInsets.all(2.0),
                                     textColor: Colors.white,
                                     //splashColor: Colors.greenAccent,
                                     elevation: 2.0,
                                     child: Container(
                                       width: 65,
                                       height: 50,
                                       decoration: BoxDecoration(
                                         image: DecorationImage(
                                             image: AssetImage('assets/tag.png'),
                                             fit: BoxFit.fill),
                                       ),
                                       child: Padding(
                                         padding: const EdgeInsets.all(16.0),
                                         child: getamountWidget(),
                                       ),
                                     ),
                                     // ),
                                     onPressed: () {
                                       print('Tapped');
                                     },
                                   ),
                                 ),

                               ])),),

                    ])
                    ),

             new Container(
               alignment: Alignment.center,
               height: 35,
               color: Colors.white,
               //padding: EdgeInsets.fromLTRB(50, 5, 0, 0),
               child: Text(
                 'kashhero.com',
                 style: TextStyle(
                   fontFamily: 'Montserrat, Regular',
                   color: '#053F4E'.toColor(),
                   fontWeight: FontWeight.w700,
                   fontSize: 14,
                 ),
                 textAlign: TextAlign.center,
               ),
             ),

           ]
      ))
    );
  }

}

Future navigateQRScene(context) async {
  Navigator.push(context, MaterialPageRoute(builder: (context) => QRScene()));
}
DavBfr commented 4 years ago

This code works, something else is wrong in your code.

import 'package:barcode_widget/barcode_widget.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  final _barcode = '/9j...iigAoo<…>';

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: BarcodeWidget(
      data: "$_barcode",
      barcode: Barcode.qrCode(),
    )));
  }
}
azeemohd786 commented 4 years ago

@DavBfr I have resolved the issue, when I tried to print the error by using,

BarcodeWidget(
       data: "$_barcodedata", // this string is directly from API(base64.string)
       barcode: Barcode.qrCode(),
      errorBuilder: (cxt, err) {
       print(err)
     }
)

The error showing was unable to encode "[47, 57, ....]"

So I have tried to change the barcode string which is getting from api as base64.string to,

 _barcodedata =_khRedemptionDetails.payload[0].barcode;  // this string is directly from API

case 1 :
           Uint8List bytes = base64.decode(_barcodedata);
           String img64 = base64Encode(bytes);
           final barcode = img64.substring(0,1200);
case 2:
          final barcode = _barcodedata.substring(0, 1200);

then, the string which is having the substring range "barcode" in above either case can be used to get QR-Code ,

BarcodeWidget(
       data: "$_barcode",
       barcode: Barcode.qrCode(),
      errorBuilder: (cxt, err) {
       print(err)
     }
)

The issue is solved, thank you for quick response comment..am closing this ticket...

DavBfr commented 4 years ago

Don't hesitate to Buy Me A Coffee.