LoginSignup
0
0
Qiita×Findy記事投稿キャンペーン 「自分のエンジニアとしてのキャリアを振り返ろう!」

[dart]A value of type 'List<String>?' can't be assigned to a variable of type 'List<String>'.のエラーの解決方法

Last updated at Posted at 2024-02-17

初めましてRinn01と申します。

エラー修正について英文のサイトしか出てこなかったので参考になれば幸いです。

'List<String>?'と'List<String>'の部分は人によって違うと思います
  
以下、上記のエラーが出るコード例です。

main1.dart
List<String> sample1; 
//変数sample1をString(文字列型)を格納したListと宣言
List<String>? sample2; 
//変数sample1をString(文字列型)を格納したListと宣言(nullもありうる)
sample1 = sample2; 
//sample2の下に波線が引かれエラー発生。

上記の例ではlist<String>型の変数にlist<String>?型の変数を代入しようとしてエラーが発生しています。エラー文を訳すとList<String>?型の変数をList<String>型の変数に割り当てられないよと言っています。他の型でも同様にエラー解消できますね。

型を合わせると以下のようにしてエラーが解消できます。

main2.dart
List<String>? sample1; 
List<String>? sample2; 
sample1 = sample2; 

また、もしくはnull safetyを含めたものが絶対にnullにはならないよ、という時にはエクスクラメーションマークを付けて次のようにしても大丈夫です。下の例の場合、もし変数sample2がnullであったらエラーが生じます。

main3.dart
List<String> sample1; 
List<String>? sample2; 
sample1 = sample2!; 

error解消の一助になると幸いです。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0