我是dev和flutter的新手。我刚刚用TextField构建了一个测试窗口小部件,当我完成输入文本时,它将调用api来连续获取并显示数据,并清除TextField中的文本,之后可以再次通过此textfield调用另一个api,在我调用的数据的Listbuilder中的新行中显示新数据。这是我的代码。
class MyApp4 extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyApp4State();
}
}
class _MyApp4State extends State<MyApp4> {
String url = 'http://test.local:8000/test/url=';
Future sap ;
TextEditingController eCtrl = TextEditingController();
List<String> _testlist = [];
@override
void initState() {
super.initState();
sap = fetchPost(url);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text('Long List App')),
body: new Container(
margin: EdgeInsets.only(top: 30.0),
child: new Column(
children: <Widget>[
Row(
children: <Widget>[
SizedBox(width: 20,),
Text('Barcode : ', style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
),),
SizedBox(width: 20,),
new Flexible(child: new TextFormField(
// autofocus: true,
controller: eCtrl,
// textInputAction: TextInputAction.done,
onFieldSubmitted: (text){
_testlist.add(text);
setState(() {
url = ( 'http://test.local:8000/test/url='+ eCtrl.text);
sap = handCheckfetch(url);
});
print(sap.toString());
print(_testlist.length.toString());
print(_testlist.asMap().toString());
print(url);
eCtrl.clear();
},
),
),
SizedBox(width: 20,),
// new Icon(Icons.check_box_outline_blank ),
// SizedBox(width: 20,),
],
),
SizedBox(height: 30,),
new Expanded(
child: ListView.builder(
itemCount: _testlist == null ? 0 : _testlist.length,
itemBuilder: (context, index) {
return FutureBuilder (future: sap, builder: (context, snapshot){
if (snapshot.hasData) {
return Container(
child: snapshot.data,
);
} return CircularProgressIndicator();
},);
}
),
)
],
)
),
);
}
}
Future handCheckfetch(String url) async {
String username = '*******';
String password = '*******';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
var response = await http.get((url),
headers: <String, String>{'authorization': basicAuth}
);
var sap = Sap.fromJson(json.decode(response.body));
if (response.statusCode == 200) {
print(response.statusCode);
// If the call to the server was successful, parse the JSON.
return
Container(
child: Row(
children: <Widget>[
SizedBox(width: 15,),
Text('Barcode : ', style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
),),
SizedBox(width: 15,),
new Text(
sap.results[0].barcode.toString(),
style: TextStyle(fontSize: 18),),
SizedBox(width: 15),
new Icon(
sap.results[0].handCheck
? Icons.check_box
: Icons.check_box_outline_blank,
size: 20,
),
SizedBox(width: 15,),
],
)
);
}
else if (response.statusCode == 500) {}
else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
当我在行中输入文本时,我想显示列表提示,其中包含来自差异api调用的许多数据,但是当我更改文本时,它总是在最后输入之后更改。对不起,糟糕的礼物:(