簡體   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