Sachihiro
Sachihiro

Reputation: 1783

Flutter: Loading local json file returns null

Sorry for my very beginner question, I am trying to teach my self Flutter so i am doing some tutorials from youtube and somehow i get Invalid argument(s) error even though i have typed exactly as it is in the tutorial, I tried to debug by printing and first it prints null and then it prints the list with json objects, but when i print mydata[0] it prints The method '[]' was called on null..

import 'package:flutter/material.dart';
import 'dart:convert';

void main() {
  runApp(new MaterialApp(
    home: new Home(),
    theme: ThemeData(
      primarySwatch: Colors.indigo,
    ),
  ));
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => new HomeState();
}

class HomeState extends State<Home> {
  List data;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("Some App"),
      ),
      body: Container(
        child: Center(
          child: FutureBuilder(
            future: DefaultAssetBundle.of(context).loadString('assets/data.json'),
            builder: (context, snapshot) {
              var mydata = json.decode(snapshot.data.toString());
              print(mydata);
              return ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Text("Name " + mydata[index]['Name']),
                        Text("Age " + mydata[index]['Age']),
                        Text("Gender " + mydata[index]['Gender']),
                      ],
                    ),
                  );
                },
                itemCount: mydata == null ? 0 : mydata.length,
              );
            },
          ),
        ),
      ),
    );
  }
}

Upvotes: 2

Views: 5594

Answers (1)

Mehmet Esen
Mehmet Esen

Reputation: 6876

First of all, don't forget the pubspec.yaml:

  assets:
   - assets/data.json

This is the json:

[
  {
    "Name": "John Doe",
    "Age": "30",
    "Gender": "Male"
  },
  {
    "Name": "Jane Doe",
    "Age": "25",
    "Gender": "Female"
  }
]

You need to check if Future delivered or not inside builder method of FutureBuilder. Like:

This is the build method:

class HomeState extends State<Home> {
  List data;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("Some App"),
      ),
      body: Container(
        child: Center(
          child: FutureBuilder(
            future:
                DefaultAssetBundle.of(context).loadString('assets/data.json'),
            builder: (context, snapshot) {
              if(!snapshot.hasData) { /// CRITICAL POINT
                return CircularProgressIndicator();
              }
              var myData = json.decode(snapshot.data);
              print(myData);
              return ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        Text("Name " + myData[index]['Name']),
                        Text("Age " + myData[index]['Age']),
                        Text("Gender " + myData[index]['Gender']),
                      ],
                    ),
                  );
                },
                itemCount: myData == null ? 0 : myData.length,
              );
            },
          ),
        ),
      ),
    );
  }
}

It's working, but I have better solution for your situation, check it:

Load and read data from Json file

Upvotes: 6

Related Questions