0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】小さいアプリの開発 シェイクスピア名句表示アプリ

Posted at

目的

  • jsonで文字列をいじってみる(decode)
  • 多少の画面装飾(Card widget)

ざっくりした仕様

  • ローカルのjson読込
  • ランダムにシェイクスピアの名句を表示
  • 更新ボタンで表示される句を変更

コード

jsonについて

デコードするとき


 import 'dart:convert';
 
 void main() {
   String jsonString = '{"name": "山田", "age": 30}';
   Map<String, dynamic> user = jsonDecode(jsonString);
   print('名前: ${user['name']}, 年齢: ${user['age']}');
 }
実際のコード
class _MyHomePageState extends State<MyHomePage> {

  String jsonStr = '';
  List json_data = [];

  @override
  void initState() {
    super.initState();
    loadJson();
  }

  Future<void> loadJson() async {
    final directory = await rootBundle.loadString('assets/quotes.json');

    setState(() {
      jsonStr = directory;
    });
    json_data = json.decode(jsonStr);
  }
  (略)
}

初期化したときにjsonをloadJson()を実行。
内容としては非同期でassets/quotes.jsonを読んでディレクトリを変数に設定→変数内のディレクトリデータを元にデコード。
setStateしないと状態が変化しないので、若干冗長になっている…ような…。

エンコードするとき

 import 'dart:convert';
 
 void main() {
   Map<String, dynamic> user = {'name': '山田', 'age': 30};
   String jsonString = jsonEncode(user);
   print(jsonString); // {"name":"山田","age":30}
 }

参考サイト

【Flutter】JSONファイルの読み書き(ローカル) - ランドノート
FlutterでのJSONシリアライズの基本:APIとのデータ変換を簡単に行う方法
【Flutter】JSONをデコードする #Flutter - Qiita
【Flutter】Card Widgetまとめ #widget - Qiita

0
0
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?