我正在尝试开发一个 TextField,它可以在数据库发生变化时更新数据。它似乎工作,但我需要防止 onChange 事件触发多次。
在 JS 中,我会使用 loash _ deounce () ,但是在 Dart 中,我不知道如何使用它。我读到过一些关于去噪库的文章,但是我不知道它们是如何工作的。
这是我的代码,这只是一个测试,所以可能有些奇怪:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ClientePage extends StatefulWidget {
String idCliente;
ClientePage(this.idCliente);
@override
_ClientePageState createState() => new _ClientePageState();
}
class _ClientePageState extends State<ClientePage> {
TextEditingController nomeTextController = new TextEditingController();
void initState() {
super.initState();
// Start listening to changes
nomeTextController.addListener(((){
_updateNomeCliente(); // <- Prevent this function from run multiple times
}));
}
_updateNomeCliente = (){
print("Aggiorno nome cliente");
Firestore.instance.collection('clienti').document(widget.idCliente).setData( {
"nome" : nomeTextController.text
}, merge: true);
}
@override
Widget build(BuildContext context) {
return new StreamBuilder<DocumentSnapshot>(
stream: Firestore.instance.collection('clienti').document(widget.idCliente).snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) return new Text('Loading...');
nomeTextController.text = snapshot.data['nome'];
return new DefaultTabController(
length: 3,
child: new Scaffold(
body: new TabBarView(
children: <Widget>[
new Column(
children: <Widget>[
new Padding(
padding: new EdgeInsets.symmetric(
vertical : 20.00
),
child: new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
new Text(snapshot.data['cognome']),
new Text(snapshot.data['ragionesociale']),
],
),
),
),
new Expanded(
child: new Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.00),
topRight: Radius.circular(20.00)
),
color: Colors.brown,
),
child: new ListView(
children: <Widget>[
new ListTile(
title: new TextField(
style: new TextStyle(
color: Colors.white70
),
controller: nomeTextController,
decoration: new InputDecoration(labelText: "Nome")
),
)
]
)
),
)
],
),
new Text("La seconda pagina"),
new Text("La terza pagina"),
]
),
appBar: new AppBar(
title: Text(snapshot.data['nome'] + ' oh ' + snapshot.data['cognome']),
bottom: new TabBar(
tabs: <Widget>[
new Tab(text: "Informazioni"), // 1st Tab
new Tab(text: "Schede cliente"), // 2nd Tab
new Tab(text: "Altro"), // 3rd Tab
],
),
),
)
);
},
);
print("Il widget id è");
print(widget.idCliente);
}
}