【问题标题】:Receive value with unspecified data type then find out the data type接收未指定数据类型的值,然后找出数据类型
【发布时间】:2020-06-17 01:10:24
【问题描述】:

为了这个问题,我在这里简化了我的案例。我想重用一个打开文本字段对话框的按钮小部件。如果按钮接收字符串数据值,则使用文本键盘,如果数据类型为 int,则使用数字键盘。我怎样才能做到这一点?这是我的代码

我的屏幕

class MyScreen1 extends StatelessWidget {
@override
Widget build(BuildContext context) {
 return Container(
   child: ReuseButton(value: 'pp'), //passing String value
  );
 }
}

可重复使用的按钮

class ReuseButton extends StatelessWidget {
final dynamic value; // receiving unspecified data type
const ReuseButton({this.value});
@override
Widget build(BuildContext context) {
  return FlatButton(
    child: Text('Enter Value'),
    onPressed: () async {
      String s = await textFieldDialog(
          context: context,
          initialValue: '',
          keyboardType: TextInputType.numberWithOptions(
              decimal: true), //here to do comparison
          title: 'Equal to');
      print(s);
    },
  );
 }
}

我已经尝试过制作一个简单类的模型

class SpecVal<T> {
T data;
SpecVal(this.data);
}

然后将我屏幕中的这些数据传递给按钮小部件

ReuseButton(value: SpecVal<String>('some value'))

但后来我很难找出 SpecVal 在按钮小部件中使用什么数据类型来进行比较

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您可以使用is 检查变量的类型。

    void main() {
      printType(42);             // 42 is an int
      printType("some string");  // some string is a String
    }
    
    void printType(dynamic value) {
      if (value is int)
        print("$value is an int");
      if (value is String)
        print("$value is a String");
    }
    

    更一般地,您可以使用value.runtimeType 检索变量的类型。

    void main() {
      printType(42);             // 42 is an int
      printType("some string");  // some string is a String
    }
    
    void printType(dynamic value) {
      Type type = value.runtimeType;
      if (type == int)
        print("$value is an int");
      if (type == String)
        print("$value is a String");
    }
    

    泛型函数/类的类型参数也是Type,所以你可以像上面一样检查它。

    void main() {
      printType<String>();  // T is a Type / the value of T is String
    }
    
    void printType<T>() {
      if (T is Type)
        print("T is a Type");
      if (T == int)
        print("the value of T is int");
      if (T == String)
        print("the value of T is String");
    }
    

    您可以通过多种方式将这些技术用于您的问题,例如您可以更改您的 SpecVal 以包含如下功能:

    class SpecVal<T> {
      ...
      bool get isString => T == String;
      ...
    }
    

    How to perform runtime type checking in Dart?相关

    【讨论】:

    • 嗨,埃德曼。为“是”投票。我不知道。谢谢.. 但是我也可能传递一个空值,我只想在传递值时指定数据类型。对不起,不是很清楚......我在 SpecVal 上面的模型上尝试过(是),如果有一些值,它可以完美工作,但是当值为 null 时,它就不起作用
    • 我更新了寻找参数类型T的答案。让我知道这是否能解决您的问题。
    • 这就是我要找的......谢谢
    猜你喜欢
    • 2022-07-20
    • 1970-01-01
    • 2017-10-26
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多