如何解决 – 类型 ‘Null’ 不是类型 ‘String’ 的子类型在类型转换中?

huangapple go评论57阅读模式
英文:

how to resolve - type 'Null' is not a subtype of type 'String' in type cast?

问题

我正在尝试从我的SQL数据库获取数据,每次我获取数据并尝试在我的应用程序上显示它时,我都会收到以下错误信息:

I/flutter (6564): 类型 'Null' 不是类型 'String' 的子类型,在类型转换中

下面的代码是从数据库中提取数据的逻辑。我已经在互联网上查找了一些源代码,其中显示我需要使用json.decode,我已经这样做,然后在控制台上打印出了数据库中的值,但是当我尝试映射这些值时,什么都不显示,因此出现了错误:

final getDataProvider = FutureProvider<List<DataModel>>((ref) async {
  return ref.watch(dataControllerProvider).getData();
});

final dataControllerProvider = Provider((ref) => DataController());

class DataController {
  Future<List<DataModel>> getData() async {
    try {
      final res = await http.get(Uri.parse(API.getDataMenu));
      List dataFromDB = jsonDecode(res.body);

      print(dataFromDB);

      return dataFromDB.map((e) => DataModel.fromJson(e)).toList();
    } catch (e) {
      print(e.toString());
      return []; // 返回一个空列表或适当处理错误情况
    }
  }
}

下面的代码是我要显示数据的地方:

Widget build(BuildContext context, WidgetRef ref) {
  final dataAsync = ref.watch(getDataProvider);
  return Scaffold(
    body: dataAsync.when(
      data: (data) {
        List<DataModel> dataList = data.map((e) => e).toList();
        return ListView.builder(
          itemCount: dataList.length,
          itemBuilder: (BuildContext context, int index) {
            return Column(
              children: [
                Text(dataList[index].Name)
              ],
            );
          },
        );
      },
      error: (error, stackTrace) => ErrorText(error: error.toString()),
      loading: () => const Loader()
    )
  );
}

希望这有助于解决你的问题。如果你需要进一步的帮助,请告诉我。

英文:

im trying to fetch data from my sql db , everytime i fetch the data and try to display it on ,my app i keep on getting the error

> I/flutter ( 6564): type 'Null' is not a subtype of type 'String' in
> type cast

the code below is the logic that pulls the data from the db , ive checked for sources on the internet where it shows I had to use json.decode , i did this then printed the values on the consoles and it displays the values from db , however when i try to map the values it shows nothing - hence the error -

final getDataProvider = FutureProvider&lt;List&lt;DataModel&gt;&gt;((ref) async {
  return ref.watch(dataControllerProvider).getData();
});

final dataControllerProvider = Provider((ref) =&gt; DataController());

class DataController {

  Future&lt;List&lt;DataModel&gt;&gt; getData() async {
    try {
      final res = await http.get(Uri.parse(API.getDataMenu));
      List dataFromDB = jsonDecode(res.body);

      print(dataFromDB);

      return dataFromDB.map((e) =&gt; DataModel.fromJson(e)).toList();
    } catch (e) {
      print(e.toString());
      return []; // Return an empty list or handle the error case appropriately
    }
  }
}

code below is where i want to display the data -

 Widget build(BuildContext context, WidgetRef ref) {
    final dataAsync = ref.watch(getDataProvider);
    return Scaffold(
        body: dataAsync.when(
            data: (data) {
              List&lt;DataModel&gt; dataList = data.map((e) =&gt; e).toList();
              return ListView.builder(
                  itemCount: dataList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Column(
                      children: [
                        Text(dataList[index].Name)
                      ],
                    );
                  });
            },
            error: (error, stackTrace) =&gt; ErrorText(error: error.toString()),
            loading: () =&gt; const Loader()));
  }
}

答案1

得分: 0

在你的DataModel中,请确保字符串值是可为空的,如下所示:

String? parameter;

另一种解决方法是在fromJson函数内进行检查,如下所示:

ChatDetailsModel.fromJson(dynamic json) {
    parameter = json['parameter'] ?? "";
}
英文:

In your DataModel make sure that the String values is nullable like that

String? parameter;

Another solution is to make a check inside fromJson function like that

 ChatDetailsModel.fromJson(dynamic json) {
    parameter = json[&#39;parameter&#39;] ?? &quot;&quot;;
 }

答案2

得分: 0

这个错误是在尝试将不同类型的值分配给已经有类型的变量时出现的。在你的情况下,你试图将一个Null值赋给一个非可为空的String类型的变量。

实际上,这行代码引发了错误:

return dataFromDB.map((e) => DataModel.fromJson(e)).toList();

我建议你查看你的DataModel,找到一个String类型的变量,并将其变为可为空。例如,让我们考虑name变量。现在它可能是这样的:

String name;

将它改成这样:

String? name;

最后,在你的UI中,添加一个可为空的表达式,像这样:

return Column(
  children: [
    Text(dataList[index].Name!.toString())
  ],
);

添加toString()是因为否则你会收到一个空安全错误。也许在显示之前添加一个if语句,以检查该值是否非空。

英文:

This error comes up when you're trying to assign a different type of value to an already typed variable. In your case, you're trying to assign a Null value to a variable that is a non-nullable type of String.

Essentially, this line is what's causing the error:

return dataFromDB.map((e) =&gt; DataModel.fromJson(e)).toList();

What I would suggest you to do is to look inside your DataModel and search for a String type of variable and make it nullable.
For eg. Let's consider the name variable.
Right now it must be like this:

String name;

Make it like this:

String? name;

And finally in your UI, add a nullable expression like this:

return Column(
  children: [
    Text(dataList[index].Name!.toString())
  ],
);

The toString() is added because you will receive a null safety error otherwise. Maybe add an if statement before displaying, to check if the value is non-null.

huangapple
  • 本文由 发表于 2023年7月10日 17:49:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652571.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定