こんにちは!本記事では、TextFieldなどで収集したStringの中身をintやdoubleにする方法など、データ形式の変換方法についてまとめました。作成したチートシートをもとに説明していきます。
![](https://www.mechengjp.com/wp-content/uploads/2022/02/Screen-Shot-2022-02-13-at-11.21.00.png)
note(ノート)
![](data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==)
![](https://assets.st-note.com/production/uploads/images/34579094/rectangle_large_type_2_57f8b9d22b8edd5dd7bcca6d883ef3fb.jpeg?fit=bounds&quality=85&width=1280)
【Dart】Stringからint, double, DateTimeに変換する|Flutterラボ
String型から別の型に変換することはFlutter開発ではよくあることなので、その方法を紹介したいと思います。 あらゆる型変換の方法のまとめて解説した動画を『Flutterラボ...
目次
StringからInt, double, DateTimeに変換する方法
TextFieldで入力された値を使って計算する場合、Textの型であるStringから計算用の型(Int, double)に変換する必要があります。その場合はparse
を使いましょう。
int.parse('100') //int型の100が出力される。
double.parse('100') //double型の100.0が出力される。
DateTimeの使い方
DateTimeは、日付を指定する表記です。
あわせて読みたい
DateTime class - dart:core library - Dart API
API docs for the DateTime class from the dart:core library, for the Dart programming language.
今を表したいときはDateTime.now()
、特定の日付を表したいときは、DateTime.utc()
を使います。
DateTimeで宣言したもののうち、たとえば年を取り出したければ、dateTime.yearで取り出せます。
また、他にもフォーマットの方法として、intlというパッケージを使用する方法もあります。
intlを使うと、下記の様にDateFormatという関数を使ってDateTime型を好きな表記に変更することができます。
import ‘package:intl/intl.dart’;
void main(){
now = DateTime.now();
String date = DateFormat(‘yyyy-MM-dd’).format(now);
}
コメント