【发布时间】:2019-06-09 13:12:24
【问题描述】:
这是我的代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget{
@override
State createState() => Comeback();
}
class Comeback extends State<MyApp>{
Widget hello(BuildContext context){
var listInsults = ['no you', 'but this applies to you more than me', 'that insult was horrible'];
var finalVar = listInsults.toList()..shuffle();
return Column(
children: <Widget>[
Row(
children: <Widget>[
CircleAvatar(
child: Text(
"XD"
)
),
Text(
finalVar[0]
)
]
)
],
);
}
Widget build(BuildContext context){
var listy = 0;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
"hi"
)
),
body: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) => hello(context),
itemCount: listy
),
),
Row(
children: <Widget>[
Expanded(
child: TextFormField(
decoration: InputDecoration(
hintText: "Insult me plz!"
)
),
),
RaisedButton(
onPressed: () {
setState(() {
listy++;
//where program is being printed
print(listy);
});
},
child: Icon(Icons.add_circle_outline),
highlightColor: Colors.amber[600]),
],
)
],
)
)
);
}
}
基本上,我正在尝试制作一个卷土重来的生成器,用户通过文本框侮辱程序,程序通过 ListView.builder 将它们烤回来。不幸的是,在测试我的代码时,没有显示程序的侮辱。正如您在代码中的注释下方看到的那样,我试图查看变量 listy(用于更改列表中的项目数)发生了什么,并意识到它只更新了一次。这是终端:
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/chatty ( 4632): uid=10091(com.example.comeback_generator) Thread-2 identical 2 lines
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/flutter ( 4632): 1
I/chatty ( 4632): uid=10091(com.example.comeback_generator) Thread-2 identical 1 line
I/flutter ( 4632): 1
从上面看,你可以看到程序显然没有更新变量 listy。如果是这样,打印的数字就会增加一。我尝试从一个类似项目中复制和粘贴代码,该项目通过更改变量和删除不必要的代码来工作和修改它。
这是我复制粘贴的代码:
onPressed: () {
if(!products.contains(myController.text.toLowerCase()) && !products.contains(myController.text.toUpperCase()) && !products.contains(myController.text)) {
setState(() {
products.add(myController.text);
_save();
_read();
});
}
},
这是我修改它的方式:
setState(() {
listy++;
print(listy);
});
修改后程序还是有同样的bug。
我的程序有什么问题? 为什么程序出错? 我该如何解决这个问题并避免将来出现类似的错误和不一致?
请记住,我是 Flutter 的初学者,很容易出错。
【问题讨论】: