Flutter&Dart,如何在扫描和更新文本时将条形码扫描值传递到TextFormField中

时间:2018-07-13 02:53:13

标签: forms dart flutter state

如何在扫描后将条形码值传递到TextForField中?条形码功能将条形码值传递给字符串条形码。这是ListTile对象,其OnTap函数定义为scan();

我想立即将该值传递回该字段。我尝试了setState()函数,但不太清楚。谢谢。

import 'dart:async';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'ItemData.dart';
import 'homepage.dart';
import 'Barcode.dart';
import 'package:flutter/services.dart';


class CreateWidget extends StatefulWidget {
  @override
  CreateState createState() => CreateState();

}
Data newData = new Data();

class CreateState extends State<CreateWidget> {
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
void submit() {
    _formKey.currentState.save();

}



  String barcode = "";

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Column(
    children: <Widget>[
      Flexible(
        flex: 0,
        child: Center(
          child: Form(
            key: this._formKey,
            child: Flex(
              direction: Axis.vertical,
              children: <Widget>[
                ListTile(
                  title: TextFormField (
                    initialValue: '',
                    decoration: new InputDecoration(
                      icon: new Icon(Icons.info),
                      hintText: "Title",
                    ),
                    validator: (val) => val.isEmpty ? null : 'Not a valid Title',
                    onSaved: (val) => newData.title = val,
              ),
            ),
            ListTile(
              title: TextFormField(
                initialValue: '',
                decoration: new InputDecoration(
                  icon: new Icon(Icons.info),
                  hintText: "Location",
                ),
                validator: (val) => val.isEmpty ? 'Location is required' : null,
                onSaved: (val) => newData.location = val,
              ),
            ),

/////////////////////////////////////// 这是我希望操作发生的列表图块。

            ListTile(
              title: TextFormField(
                initialValue: '',
                decoration: new InputDecoration(
                  icon: new Icon(Icons.info),
                  hintText: "Barcode",
                ),
                validator: (val) => val.isEmpty ? 'Barcode is required' : null,
                onSaved: (val) => newData.barcode = val,
              ),
              trailing: new Icon(Icons.search),
              onTap: () {
                {scan();}
              },
            ),
            ListTile(
              title: TextFormField(
                initialValue: '',
                decoration: new InputDecoration(
                  icon: new Icon(Icons.info),
                  hintText: "Type",
                ),
                validator: (val) => val.isEmpty ? 'Type is required' : null,
                onSaved: (val) => newData.type = val,
              ),
            ),
            ListTile(
              leading: Icon(Icons.access_time),
              title: Text(_getDateNow()),
            ),
            RaisedButton(
              color: Colors.red,
              textColor: Colors.white,
              child: new Text('Create'),
              onPressed: () {
                submit();
                createItem();
                Navigator.pop(context, true);

                },
              ),
            ],
          ),
        ),
      ),
    )
  ],
);
  }

 Future scan() async {
try {
  String barcode = await BarcodeScanner.scan();
  setState(() => this.barcode = barcode);
} on PlatformException catch (e) {
  if (e.code == BarcodeScanner.CameraAccessDenied) {
    setState(() {
      this.barcode = 'The user did not grant the camera permission!';
    });
  } else {
    setState(() => this.barcode = 'Unknown error: $e');
  }
} on FormatException{
  setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
} catch (e) {
  setState(() => this.barcode = 'Unknown error: $e');
    }
  }


}

Future createItem() async {
  Firestore.instance.runTransaction((Transaction transaction) async {
  CollectionReference reference = 
  Firestore.instance.collection('items');
  await reference.add({"title": newData.title, "location": newData.location, "type": newData.type,"date": _getDateNow(), "editing": false, "barcode": newData.barcode,});

  });
}

_getDateNow() {
  var now = new DateTime.now();
  var formatter = new DateFormat('MM-dd-yyyy H:mm');
  return formatter.format(now);
}

2 个答案:

答案 0 :(得分:0)

对于“来自字段的文本”,请按照以下步骤在其中初始化字符串条形码的控制器上:-

TextEditingContoller c = new TextEditingController();

并在文本表单字段内的列表块中将其控制器设置为c,并在列表块的ontap函数内执行此操作。

scan().then(()=>setState((){
    c.text = barcode;
}));

然后函数使用一个在编写代码时会自动向您建议的参数。我只在VSCode和android studio中尝试过。 因此,请确保传递正确的参数以使功能起作用,否则可能会出错。

答案 1 :(得分:0)

因此,看起来then()需要声明一个类型。传递String修复了它。

scan().then((String)=>setState((){
    c.text = barcode;
}));