Flutter 加载本地json文件

import 'dart:convert';

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  late List data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Load local JSON file"),
        ),
        body: Container(
          child: Center(
            // 使用FutureBuilder和DefaultAssetBundle去加载当地json文件
            child: FutureBuilder(
                future: DefaultAssetBundle
                    .of(context)
                    .loadString('images/data_repo/starwars_data.json'),
                builder: (context, snapshot) {
                  // Decode the JSON
                  var new_data = json.decode(snapshot.data.toString());

                  return ListView.builder(
                    // Build the ListView
                    itemBuilder: (BuildContext context, int index) {
                      return Card(//卡片就是每个item
                        child: Column(//卡片里面的内容是按列排布的
                          crossAxisAlignment: CrossAxisAlignment.stretch,//该item扩充全部
                          children: <Widget>[//里面的内容
                            Text("Name: " + new_data[index]['name']),
                            Text("Height: " + new_data[index]['height']),
                            Text("Mass: " + new_data[index]['mass']),
                            Text(
                                "Hair Color: " + new_data[index]['hair_color']),
                            Text(
                                "Skin Color: " + new_data[index]['skin_color']),
                            Text(
                                "Eye Color: " + new_data[index]['eye_color']),
                            Text(
                                "Birth Year: " + new_data[index]['birth_year']),
                            Text("Gender: " + new_data[index]['gender'])
                          ],
                        ),
                      );
                    },
                    itemCount: new_data == null ? 0 : new_data.length,
                  );
                }),
          ),
        ));
  }
}

Flutter 加载本地json文件_第1张图片

你可能感兴趣的:(安卓,android)