flutter - for 循环出错:Flutter 中需要一个标识符
问题描述
我从列表中一一获取数字以使用telephony
包发送短信,但在我的容器内,它给了我一个error at for loop
. 请让我知道如何避免此错误
我的代码是:
import 'dart:async';
import 'package:epicare/Homepage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:telephony/telephony.dart';
class TriggeringAlert extends StatefulWidget {
const TriggeringAlert({Key key, this.device}) : super(key: key);
final BluetoothDevice device;
@override
_TriggeringAlertState createState() => _TriggeringAlertState();
}
class _TriggeringAlertState extends State<TriggeringAlert> {
// Get location
Position _currentPosition;
String _currentAddress;
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
void initState(){
startTimer();
_getCurrentLocation();
getCaregivers();
super.initState();
}
Timer _timer;
int _start = 10;
void startTimer() {
if (_timer != null) {
_timer.cancel();
_timer = null;
} else {
_timer = new Timer.periodic(
const Duration(seconds: 1),
(Timer timer) => setState(
() {
if (_start < 1) {
timer.cancel();
} else {
_start = _start - 1;
}
},
),
);
}
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress = "${place.locality}, ${place.country}";
});
} catch (e) {
print(e);
}
}
// Send SMS
final Telephony telephony = Telephony.instance;
sendSMS(String number) {
if (_currentPosition != null && _currentAddress != null)
print('Address $_currentAddress');
telephony.sendSms(
to: number,
message:
"This is to inform you that Epilepsy attack is occurring right now\n My current Location is: $_currentAddress",
);
}
User cuser = FirebaseAuth.instance.currentUser;
final fb = FirebaseDatabase.instance.reference().child("User_data");
List<String> numbers_list = List();
//Caregivers
void getCaregivers() {
// Firebase
fb
.child(cuser.uid)
.child("caregivers")
.once()
.then((DataSnapshot snapshot) {
var data = snapshot.value;
data.forEach((key, value) {
setState(() {
numbers_list.add(value['Caregiver_Number']);
});
});
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: const Color(0xffe8e5af),
body: Column(
children: [
Container(
width: size.width,
padding: EdgeInsets.only(top: 70),
child: Text(
'TRIGGERING ALERT IN',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w800,
fontSize: 21,
color: const Color(0xff000000),
height: 1.380952380952381,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Container(
width: size.width * 0.6,
padding: EdgeInsets.only(top: 21),
child: Text(
'If it is a false alarm please cancel the alert ',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w600,
fontSize: 15,
color: const Color(0xa8000000),
height: 1.3333333333333333,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Center(
child: Container(
//color: Colors.white,
height: size.height * 0.5,
alignment: Alignment.center,
//padding: EdgeInsets.only(bottom: 100),
child: Stack(
alignment:AlignmentDirectional.center,
children: [
Container(
//color: Colors.yellow,
padding: EdgeInsets.only(bottom:35),
child: Text(
'$_start',
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 50,
color: const Color(0xff000000),
letterSpacing: 5,
fontWeight: FontWeight.w600,
height: 0.7,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Container(
//color: Colors.yellow,
padding: EdgeInsets.only(top:45),
child: Text(
'Seconds',
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 14,
color: const Color(0xff000000),
letterSpacing: 1.4000000000000001,
fontWeight: FontWeight.w600,
height: 2.5,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Transform.scale(
scale: 5,
child: CircularProgressIndicator(
backgroundColor: const Color(0x26a4a67f),
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.black)),
),
],
),
),
),
SizedBox(
height: 90,
),
Container(
//padding: EdgeInsets.only(bottom: 85),
alignment: Alignment.center,
child: _start==0
? numbers_list.length == 0
? Fluttertoast.showToast(msg: "No caregivers")
:(
for (int i = 0; i < numbers_list.length; i++)
{
sendSMS(numbers_list[i].toString());
}
)
: ButtonTheme(
height: 50.0,
minWidth: 200.0,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28)),
color: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return Homepage(device: widget.device,);
},
),
);
},
child: Text(
"Cancel Alert",
style: TextStyle(
fontSize: 14.0,
fontFamily: 'Montserrat',
color: const Color(0xffd4d411),
fontWeight: FontWeight.w700,
),
),
),
),
)
],
),
);
}
}
for循环的错误:
error: Expected to find ')'
error: Expected an identifier
解决方案
你可以试试这个:
基本上我所做的是将发送 SMS 的代码移动到你的startTimer()
方法中,10 秒后,“取消警报”按钮将消失并被一个空的 SizedBox 取代。
import 'dart:async';
import 'package:epicare/Homepage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:telephony/telephony.dart';
class TriggeringAlert extends StatefulWidget {
const TriggeringAlert({Key key, this.device}) : super(key: key);
final BluetoothDevice device;
@override
_TriggeringAlertState createState() => _TriggeringAlertState();
}
class _TriggeringAlertState extends State<TriggeringAlert> {
// Get location
Position _currentPosition;
String _currentAddress;
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
void initState(){
startTimer();
_getCurrentLocation();
getCaregivers();
super.initState();
}
Timer _timer;
int _start = 10;
void startTimer() {
if (_timer != null) {
_timer.cancel();
_timer = null;
} else {
_timer = new Timer.periodic(
const Duration(seconds: 1),
(Timer timer) => setState(
() {
if (_start < 1) {
timer.cancel();
if (numbers_list.length == 0) Fluttertoast.showToast(msg: "No caregivers");
else {
for (int i = 0; i < numbers_list.length; i++) {
sendSMS(numbers_list[i].toString());
}
}
} else {
_start = _start - 1;
}
},
),
);
}
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress = "${place.locality}, ${place.country}";
});
} catch (e) {
print(e);
}
}
// Send SMS
final Telephony telephony = Telephony.instance;
sendSMS(String number) {
if (_currentPosition != null && _currentAddress != null)
print('Address $_currentAddress');
telephony.sendSms(
to: number,
message:
"This is to inform you that Epilepsy attack is occurring right now\n My current Location is: $_currentAddress",
);
}
User cuser = FirebaseAuth.instance.currentUser;
final fb = FirebaseDatabase.instance.reference().child("User_data");
List<String> numbers_list = List();
//Caregivers
void getCaregivers() {
// Firebase
fb
.child(cuser.uid)
.child("caregivers")
.once()
.then((DataSnapshot snapshot) {
var data = snapshot.value;
data.forEach((key, value) {
setState(() {
numbers_list.add(value['Caregiver_Number']);
});
});
});
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: const Color(0xffe8e5af),
body: Column(
children: [
Container(
width: size.width,
padding: EdgeInsets.only(top: 70),
child: Text(
'TRIGGERING ALERT IN',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w800,
fontSize: 21,
color: const Color(0xff000000),
height: 1.380952380952381,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Container(
width: size.width * 0.6,
padding: EdgeInsets.only(top: 21),
child: Text(
'If it is a false alarm please cancel the alert ',
style: TextStyle(
fontFamily: 'Montserrat',
fontWeight: FontWeight.w600,
fontSize: 15,
color: const Color(0xa8000000),
height: 1.3333333333333333,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Center(
child: Container(
//color: Colors.white,
height: size.height * 0.5,
alignment: Alignment.center,
//padding: EdgeInsets.only(bottom: 100),
child: Stack(
alignment:AlignmentDirectional.center,
children: [
Container(
//color: Colors.yellow,
padding: EdgeInsets.only(bottom:35),
child: Text(
'$_start',
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 50,
color: const Color(0xff000000),
letterSpacing: 5,
fontWeight: FontWeight.w600,
height: 0.7,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Container(
//color: Colors.yellow,
padding: EdgeInsets.only(top:45),
child: Text(
'Seconds',
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 14,
color: const Color(0xff000000),
letterSpacing: 1.4000000000000001,
fontWeight: FontWeight.w600,
height: 2.5,
),
textHeightBehavior:
TextHeightBehavior(applyHeightToFirstAscent: false),
textAlign: TextAlign.center,
),
),
Transform.scale(
scale: 5,
child: CircularProgressIndicator(
backgroundColor: const Color(0x26a4a67f),
strokeWidth: 2.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.black)),
),
],
),
),
),
SizedBox(
height: 90,
),
Container(
//padding: EdgeInsets.only(bottom: 85),
alignment: Alignment.center,
child: _start == 0
? SizedBox.shrink()
: ButtonTheme(
height: 50.0,
minWidth: 200.0,
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28)),
color: Colors.black,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return Homepage(device: widget.device,);
},
),
);
},
child: Text(
"Cancel Alert",
style: TextStyle(
fontSize: 14.0,
fontFamily: 'Montserrat',
color: const Color(0xffd4d411),
fontWeight: FontWeight.w700,
),
),
),
),
)
],
),
);
}
}
推荐阅读
- kotlin - Geany 对 Kotlin 的支持
- android - 在 kotlin 中,如何创建个人资料图片并将联系人姓名的首字母显示为离线短信应用中的个人资料图片?
- javascript - 如何在javascript中为数组中的每个对象分配一个随机数?
- apache - 在 apache nifi 中使用 ListSFTP 处理器连接到 AWS EC2
- database - Wix Corvid 数据库过滤条件
- r - 如何将日历日期添加到现有数据表中,以便在 R 中计算整个月份?
- sql-server - 如何在sql server中构建动态过滤查询
- python - 如何在 Python 的 Tkinter 中更改按钮的颜色
- bash - 在 bin/sh 脚本中使用 scp 命令失败并出现语法错误
- java - 无法将 Intent Extras 从 Activity 传递到 Viewpager 中的片段