flutter 返回类型'String'不是'void',这是闭包的上下文所要求的

kcrjzv8t  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(221)

我试图创建一个函数,它显示一个带有文本表单字段的AlertDialog。用户将在此字段中输入值,然后按“确定”按钮。我想返回输入的字符串值时,确定按钮按下。但是我在返回行得到了 The return type 'String' isn't a 'void',as required by the closure's context. 错误。还获取 * 主体可能正常完成,导致返回'null',但返回类型'String'在第一行可能是不可空的类型 * 错误。
我该怎么办?

String enterValue(TextInputType keyType) {
    String girilenDeger = '';
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('enter_value').tr(),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextFormField(
              style: const TextStyle(fontSize: 18, color: Colors.black),
              initialValue: '',
              keyboardType: keyType,
              autofocus: true,
              onChanged: (val) {
                girilenDeger = val;
              },
            ),
          ],
        ),
        actions: [
          ElevatedButton(
            onPressed: () {
              return girilenDeger;
            },
            child: const Text('ok').tr(),
          ),
        ],
      ),
    );
  }
uoifb46i

uoifb46i1#

请试试这个

Future<String> enterValue(TextInputType keyType) async {
    String girilenDeger = '';
    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('enter_value'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextFormField(
              style: const TextStyle(fontSize: 18, color: Colors.black),
              initialValue: '',
              keyboardType: keyType,
              autofocus: true,
              onChanged: (val) {
                girilenDeger = val;
              },
            ),
          ],
        ),
        actions: [
          ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('ok')),
        ],
      ),
    );

    return girilenDeger;
  }

顺便说一句,我删除你的.tr()

相关问题