4

I'm working with flutter application.I fetch demo json file dummy JSON file using this URL fetching JSON value.but when I try by adding json file created in the assets folder and file directory path I added in the code. but it's not working and in pubspec.yaml file I added like this

assets: - assets/test.json.

import 'package:flutter/services.dart' show rootBundle;

Future<Map> _loadAStudentAsset() async { return await rootBundle.loadString('assets/test.json'); }

What I'm doing wrong here. Can anyone suggest me? How to work with json file which is present in the same project folder. And feel free to tell is there any mistakes in my code. Here is my working code.

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';

 Map data;
 List features; // features object list
void main() async {
data = await getQuakes();

features = data['features'];

 //print(_data['features'][0]['properties']);

 runApp(new MaterialApp(
   title: 'Quakes',
   home: new Quakes(),
  ));
}

class Quakes extends StatelessWidget {
   @override
   Widget build(BuildContext context) {
     return new Scaffold(
       appBar: new AppBar(
        title: new Text('Quakes'),
        centerTitle: true,
        backgroundColor: Colors.red,
       ),
  body: new Center(
    child: new ListView.builder(
        itemCount: features.length,
        padding: const EdgeInsets.all(15.0),
        itemBuilder: (BuildContext context, int position) {
          //crating the rows for our listview
          if (position.isOdd) return new Divider();
          final index = position ~/
              2; // we are dividing position by 2 and returning an integer result

          var format = new DateFormat.yMMMMd("en_US").add_jm();
          //var dateString = format.format(date);
          var date = format.format(new DateTime.fromMicrosecondsSinceEpoch(
              features[index]['properties']['time'] * 1000,
              isUtc: true));

          return new ListTile(
            title: new Text(
              " $date",
              //title: new Text("Date: $date",
              style: new TextStyle(
                  fontSize: 15.5,
                  color: Colors.orange,
                  fontWeight: FontWeight.w500),
            ),
            subtitle: new Text(
              "${_features[index]['properties']['place']}",
              style: new TextStyle(
                  fontSize: 14.5,
                  fontWeight: FontWeight.normal,
                  color: Colors.grey,
                  fontStyle: FontStyle.italic),
            ),
            leading: new CircleAvatar(
              backgroundColor: Colors.green,
              child: new Text(
                "${_features[index]['properties']['mag']}",
                style: new TextStyle(
                    fontSize: 16.5,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                    fontStyle: FontStyle.normal),
              ),
            ),
            onTap: () {
              showAlertMessage(
                  context, "${_features[index]['properties']['title']}");
            },
          );
        }),
  ),
);
}

   void _showAlertMessage(BuildContext context, String message) {
      var alert = new AlertDialog(
      title: new Text('Quakes'),
      content: new Text(message),
      actions: <Widget>[
           new FlatButton(
             onPressed: () {
                Navigator.pop(context);
             },
           child: new Text('OK'))
      ],
     );
  showDialog(context: context, builder: (context) => alert);
 }
}

Future<Map> getQuakes() async {
 String apiUrl = 
 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';

   http.Response response = await http.get(apiUrl);

   return json.decode(response.body);
 }
3
  • is ur tests.json directly under assets folder or is there a folder between them? Do you get any error also? Commented Aug 10, 2018 at 7:20
  • stackoverflow.com/questions/49757953/… Commented Aug 10, 2018 at 7:22
  • @PeterHaddad Getting these erorrs compiler message: lib/main.dart:80:10: Error: A value of type 'dart.core::String' can't be assigned to a variable of type 'dart.async::FutureOr<dart.core::List<dynamic>>'. compiler message: Try changing the type of the left hand side, or casting the right hand side to 'dart.async::FutureOr<dart.core::List<dynamic>>'. compiler message: return await rootBundle.loadString('assets/test.json'); compiler message: ^ Commented Aug 10, 2018 at 7:43

1 Answer 1

3

First, import the services package

import 'package:flutter/services.dart' show rootBundle;

Then, change this:

Future<Map> _loadAStudentAsset() async {
  return await rootBundle.loadString('assets/test.json');
}

into this:

Future<String> _loadAStudentAsset() async {
  return await rootBundle.loadString('assets/test.json');
}

loadString() method returns a Future of type String.

Check here: https://docs.flutter.io/flutter/services/AssetBundle/loadString.html

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.when I was changed to String. print(_data[0] [' title ']); line getting these error String can't be assigned to the parameter type int
i wrote after getQuakes(); method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.