繁体   English   中英

如何创建 If 语句以将值添加到 Flutter 中的列表

[英]How to create an If statement to add values to List in Flutter

所以我正在尝试发送一个将添加到 displaycontact_list 的值,但是我想事先创建一个 if 语句来检查该值是数字还是字符串,如果它是一个数字,它将基于添加列表Contact.phones.first.number 如果它是一个字符串,它将根据 Contact.name.first 添加列表

这就是我坚持的,我已经坚持了几个小时

 class _PulsaNewScreenState extends State<PulsaNewScreen> {
  _prefixImage() {
    return InkWell(
      child: Image.asset(
        AssetsImages.redbank_kontak,
        scale: 3,
      ),
    );
  }

  bool isNumericUsingRegularExpression(String string) {
    final numericRegex = RegExp(r'^-?(([0-9]*)|(([0-9]*)\.([0-9]*)))$');

    return numericRegex.hasMatch(string);
  }

  bool isSearch = false;
  List<Contact>? contacts;
  late List<Contact> displaycontact_list = List.from(contacts!);

  void updateList(String value) {
    print(value);
    print(isNumericUsingRegularExpression(value));
    setState(() {
      if (isNumericUsingRegularExpression(value) == true) {
        print("its in hereee");
        displaycontact_list = contacts!
            .where((element) => element.phones.first!.number.contains(value))
            .toList();
        print("completed");
        print(displaycontact_list);
      } else {
        print("not in there how??");
        displaycontact_list = contacts!
            .where((element) =>
                element.name.first!.toLowerCase().contains(value.toLowerCase()))
            .toList();
      }

      print(displaycontact_list);
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getContact();
  }

  void getContact() async {
    if (await FlutterContacts.requestPermission()) {
      contacts = await FlutterContacts.getContacts(
          withProperties: true, withPhoto: true);
      print(contacts);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        // appBar: customAppBar(context, 'Pulsa'),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Column(
            children: [
              NewAppBar2("Pulsa"),
              Padding(
                padding: EdgeInsets.symmetric(
                  horizontal: ResponsiveSize.width(context, 0.05),
                  vertical: 10,
                ),
                child: customTextFormField(
                  context,
                  action: TextInputAction.done,
                  textSize: 14,
                  vertical: 0,
                  prefixIcon: _prefixImage,
                  hint: "Input Phone number",
                  change: (value) {
                    print(displaycontact_list);
                    setState(() {
                      isSearch = true;
                    });
                    updateList(value);
                  },
                ),
              ),
              SizedBox(
                height: 20,
              ),
              (contacts == null)
                  ? Center(child: CircularProgressIndicator())
                  : Expanded(
                      child: ListView.builder(
                        physics: BouncingScrollPhysics(),
                        itemCount: !isSearch
                            ? contacts!.length
                            : displaycontact_list.length,
                        itemBuilder: (BuildContext context, int index) {
                          Uint8List? image = contacts![index].photo;
                          Uint8List? image2 = displaycontact_list![index].photo;

                          String num = (contacts![index].phones.isNotEmpty)
                              ? (contacts![index].phones.first.number)
                              : "--";

                          String num2 =
                              (displaycontact_list![index].phones.isNotEmpty)
                                  ? (displaycontact_list![index]
                                      .phones
                                      .first
                                      .number)
                                  : "--";

                          return !isSearch
                              ? ListTile(
                                  leading: (contacts![index].photo == null)
                                      ? const CircleAvatar(
                                          backgroundColor: Colors.black,
                                          child: CircleAvatar(
                                            child: Icon(
                                              Icons.person,
                                              color: ThemeColors.redbankRed,
                                            ),
                                            backgroundColor: Colors.white,
                                          ),
                                        )
                                      : CircleAvatar(
                                          backgroundImage: MemoryImage(image!),
                                        ),
                                  title: Text(
                                      "${contacts![index].name.first} ${contacts![index].name.last}"),
                                  subtitle: Text(num),
                                  onTap: () {
                                    /* if (contacts![index].phones.isNotEmpty) {
                                  launch('tel: ${num}');
                                }*/
                                  })
                              : ListTile(
                                  leading: (displaycontact_list![index].photo ==
                                          null)
                                      ? const CircleAvatar(
                                          backgroundColor: Colors.black,
                                          child: CircleAvatar(
                                            child: Icon(
                                              Icons.person,
                                              color: ThemeColors.redbankRed,
                                            ),
                                            backgroundColor: Colors.white,
                                          ),
                                        )
                                      : CircleAvatar(
                                          backgroundImage: MemoryImage(image2!),
                                        ),
                                  title: Text(
                                      "${displaycontact_list![index].name.first} ${displaycontact_list![index].name.last}"),
                                  subtitle: Text(num2),
                                  onTap: () {
                                    /* if (contacts![index].phones.isNotEmpty) {
                                  launch('tel: ${num}');
                                }*/
                                  });
                        },
                      ),
                    ),
              SizedBox(
                height: 20,
              ),
            ],
          ),
        ));
  }
}

我试图在 onchanged 之后创建一个 if 语句来检查 val 是否为数字,如果它是数字,它将返回 true,如果不是,它将返回 false。 if语句实际上进入if语句并在它是数字时打印“its in hereee”,当它是字符串时它在if语句之外进入else语句但是它似乎没有将它添加到列表中虽然它在 If 语句中。 希望得到一些指导。 谢谢

当前程序输出这个错误码

======== Exception caught by widgets ===============================================================
The following StateError was thrown while calling onChanged:
Bad state: No element

When the exception was thrown, this was the stack: 
#0      List.first (dart:core-patch/growable_array.dart:343:5)
#1      _PulsaNewScreenState.updateList.<anonymous closure>.<anonymous closure> (package:Redbank/src/presentation/screens/pulsa_prabayar_screen/pulsa_new_screen.dart:46:48)
#2      WhereIterator.moveNext (dart:_internal/iterable.dart:439:13)
#3      new _GrowableList._ofOther (dart:core-patch/growable_array.dart:202:26)
#4      new _GrowableList.of (dart:core-patch/growable_array.dart:152:26)
#5      new List.of (dart:core-patch/array_patch.dart:51:28)
#6      Iterable.toList (dart:core/iterable.dart:470:12)
#7      _PulsaNewScreenState.updateList.<anonymous closure> (package:Redbank/src/presentation/screens/pulsa_prabayar_screen/pulsa_new_screen.dart:47:14)

问题可能是因为element.phones OR element.name是空的,所以当您尝试在空列表上调用element.name.first时,它会抛出给定的错误,

所以你的支票应该改为:

if (isNumericUsingRegularExpression(value) == true)
    displaycontact_list = contacts!
        .where((element){
            if(element.phones.isEmpty) return false;
            return element.phones.first!.number.contains(value);
        })
        .toList();

else
    displaycontact_list = contacts!
        .where((element){
            if(element.name.isEmpty) return false;
            return element.name.first!.toLowerCase().contains(value);
        })
        .toList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM