flutter - 第一次颤动后如何停止循环
问题描述
我制作了一种使用 Loop 将图像保存到数据库的方法。现在的问题是当我运行代码时,代码到达末尾后,它又回来并再次工作,并且数据被保存并重复了不止一次。
控制台代码:
D/InputTransport(27530): Input channel constructed: fd=97
D/ViewRootImpl@43d64bf[MainActivity](27530): ViewPostIme pointer 0
D/ViewRootImpl@43d64bf[MainActivity](27530): ViewPostIme pointer 1
I/flutter (27530): Test_Code 200
I/flutter (27530): Test_Code 200
I/flutter (27530): Test_Code 200
I/flutter (27530): Test_Code 200
保存日期代码:
void SaveDate() async {
for(int i=0;i<imagecode.length;i++) {
var url = uploadEndPoint;
var response = await http.post(url, body: {
"image": imagecode[i],
"NameImage": name[i],
});
if (response.statusCode == 200) {
print('Test_Code ${response.statusCode}');
} else {
}
}
}
完整代码:
void main() {
runApp(
MyApp(),
);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: PickImages(),
);
}
}
class PickImages extends StatefulWidget {
@override
_PickImagesState createState() => _PickImagesState();
}
class _PickImagesState extends State<PickImages> {
static final String uploadEndPoint = 'https://****************.php';
List<Object> images = List<Object>();
Future<File> _imageFile;
bool _isVisible = false;
String base64Image;
List imagecode=[];
List name=[];
Future _onAddImageClick(int index, int type) async {
if (images != null)
setState(() {
_imageFile = ImagePicker.pickImage(
source: type == 1 ? ImageSource.camera : ImageSource.gallery,
imageQuality: 50,
);
getFileImage(index);
});
}
void getFileImage(int index) async {
_imageFile.then((file) async {
setState(() {
ImageUploadModel imageUpload = new ImageUploadModel();
imageUpload.imageFile = file;
images.replaceRange(index, index + 1, [imageUpload]);
});
});
}
void showImageBox() {
setState(() {
_isVisible = !_isVisible;
});
}
@override
void initState() {
super.initState();
setState(() {
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
images.add("Add Image");
});
}
void SaveDate() async {
for(int i=0;i<imagecode.length;i++) {
var url = uploadEndPoint;
var response = await http.post(url, body: {
"image": imagecode[i],
"NameImage": name[i],
});
if (response.statusCode == 200) {
print('Test_Code ${response.statusCode}');
} else {
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Post Images'),
),
body: Column(
children: <Widget>[
Container(
//padding: EdgeInsets.only(right: 5),
child: Card(
elevation: 5,
child: ListTile(
trailing: Icon(Icons.attachment),
title: Text('Attachments'),
onTap: () {
showImageBox();
},
),
),
),
Visibility(
visible: _isVisible,
child: Padding(
padding: const EdgeInsets.only(top: 5.0, right: 5.0),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 3,
childAspectRatio: 1,
children: List.generate(images.length, (index) {
if (images[index] is ImageUploadModel) {
ImageUploadModel uploadModel = images[index];
if(uploadModel.imageFile!=null){
//base64 image
List<int> imageBytes = uploadModel.imageFile.readAsBytesSync();
// base64Image = base64Encode(snapshot.data.readAsBytesSync());
base64Image = base64Encode(imageBytes); //'base64Image' holds the base64 image string
imagecode.add(base64Image);
name.add(uploadModel.imageFile.path.split("/").last);}
return Card(
clipBehavior: Clip.antiAlias,
child: Stack(
children: <Widget>[
Image.file(
uploadModel.imageFile,
fit: BoxFit.cover,
width: 300,
height: 300,
),
Positioned(
right: 5,
top: 5,
child: InkWell(
child: Icon(
Icons.remove_circle,
size: 20,
color: Colors.red,
),
onTap: () {
setState(() {
images.replaceRange(
index, index + 1, ['Add Image']);
});
},
),
),
],
),
);
} else {
return Card(
child: IconButton(
icon: Icon(Icons.camera_alt),
onPressed: () {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Camera'),
onTap: () {
_onAddImageClick(index, 1);
Navigator.of(context).pop();
},
),
new ListTile(
leading:
new Icon(Icons.photo_library),
title: new Text('Gallery'),
onTap: () {
_onAddImageClick(index, 2);
Navigator.of(context).pop();
}),
],
),
),
);
},
);
},
),
);
}
}),
),
),
),
RaisedButton(
child: Text('send'),
onPressed: () {
SaveDate();
},
),
],
),
);
}
}
class ImageUploadModel {
File imageFile;
ImageUploadModel({
this.imageFile,
});
}
解决方案
这是一个与How to stop/break forEach loop in dart /flutter非常相似的问题?
由于您使用的是常规 for 循环,break;
这是该语言的一项功能,只要满足您的条件,您就可以跳出循环
推荐阅读
- swagger - 如何在 Swagger UI 中的 API 模型中显示互斥字段
- javascript - 无法使用模板文字获取元素
- javascript - Reactjs - 地图函数内的多个if条件
- python-3.x - 在 python 中使用来自 imshow() 的缩放图像
- java - 为什么 kotlin 在 foreach 中创建两个对象时抛出“验证程序拒绝类”错误?
- slack - slack bot 和表单控件不调用外部 api
- ruby-on-rails - 如何显示 has_many :through 与 ActiveModel::Serializer 的关联
- html - 显示方向
- sql-server - 无法从 SSMS 连接到 AWS 数据库
- firebase - 如何知道观察值是否通过验证?