首页 > 解决方案 > 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

标签: flutterdart

解决方案


你可以试试这个:
基本上我所做的是将发送 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,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

推荐阅读