Flutter のアプリ開発でtype ‘Null’ is not a subtype of type ‘String’ in type castと表示されて、どう対応したら良いのか分からない。
- type ‘Null’ is not a subtype of type ‘String’ in type castエラーの対処法
- nullsafetyとは
ちなみに、Flutterのスキルを0から効率的に伸ばす方法は、仕事として実務を経験することです。そして、最速で転職・就職・副業するには学習をどんどん進め、ポートフォリオを最優先で完成させましょう!応募できそうなFlutter案件をチェックすると必要なスキルも分かり学習に身が入ります!Flutter案件/求人の探し方はコチラで詳しく解説していますので、ご参考にして下さい。
事象「Flutterエラー対応)Error: type ‘Null’ is not a subtype of type ‘String’ in type cast」
開発環境
モデル | MacBook Air 2020 |
CPU・GPU | M1(GPU8コア GPU8コア) |
メモリ | 16GB |
SSD | 512GB |
Flutter | 3.3.0 |
Dart | 2.18.0 |
エラー内容
======== Exception caught by widgets library =======================================================
The following _CastError was thrown building XXXX(dirty):
type 'Null' is not a subtype of type 'String' in type cast
原因:Null Safety
エラー原因のソースコード
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final List<Map<String, Object>> questions;
final int questionIndex;
final Function answerQuestion;
Quiz({
required this.questions,
required this.answerQuestion,
required this.questionIndex
});
@override
Widget build(BuildContext context) {
return Column(
children: [
Question(
questions[questionIndex]['questionText']as String
),
...(questions[questionIndex]['answers'] as List<Map<String,Object>>).map((answer) {
return Answer(() => answerQuestion(answer['score']), answer['text']as String);
}).toList()
],
);
}
}
dart 2.12 からNull Safetyになりました。
Dart 2.12 より前は、アプリ実行時にNullPointerExceptionとなりシステムエラーとなってました。現在はコンパイル時にエラーとなるのです。
対処方法:to String
対応後のソースコード
import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final List<Map<String, Object>> questions;
final int questionIndex;
final Function answerQuestion;
Quiz({
required this.questions,
required this.answerQuestion,
required this.questionIndex
});
@override
Widget build(BuildContext context) {
return Column(
children: [
Question(
questions[questionIndex]['questionText'].toString(),
),
...(questions[questionIndex]['answers'] as List<Map<String,Object>>).map((answer) {
return Answer(() => answerQuestion(answer['score']), answer['text'].toString());
}).toList()
],
);
}
}
as string
の箇所を.tostring()
に修正し正常に動作。
まとめ:type ‘Null’ is not a subtype of type ‘String’ in type castはto Stringで対応
今回の記事では、Flutter のアプリ開発でtype ‘Null’ is not a subtype of type ‘String’ in type castと表示されて、どう対応したら良いのか分からない時の対処法について解説しました。
- to Stringで対応
Flutterエンジニアになるには?
初心者が中級者レベルのFlutterエンジニアなるまでの進め方をまとめました。
Flutterの学習方法を知る

Flutter をスクールで学ぶ

Flutterの副業を探す

おまけ:Flutter入門の完全ガイド

Flutter/Dartの基礎一覧
Flutter/Dartの入門知識として押さえておきたい内容をまとめました。学習のご参考にどうぞ。
- ローカルデータベース(SQLite)
- グラフ①(fl_chart)
- グラフ②(syncfusion_flutter_charts)
- カレンダーから日付取得①(syncfusion_flutter_datepicker)
- カレンダーから日付取得②(month_picker_dialog_2)