【问题标题】:JSON parsing in flutter颤振中的JSON解析
【发布时间】:2019-01-17 17:21:27
【问题描述】:

我正在使用颤振应用程序。我获取演示 json 文件 dummy JSON file 使用此 URL 获取 JSON 值。但是当我尝试添加在资产文件夹和文件目录路径中创建的 json 文件时,我在代码中添加了。但它不起作用,我在pubspec.yaml 文件中添加了这样的

assets: - assets/test.json.

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

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

我在这里做错了什么。任何人都可以建议我吗?如何使用存在于同一项目文件夹中的 json 文件。并且随时告诉我的代码中是否有任何错误。 这是我的工作代码。

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);
 }

【问题讨论】:

  • 你的tests.json是直接在assets文件夹下还是它们之间有文件夹?你也有任何错误吗?
  • @PeterHaddad 得到这些错误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&lt;dart.core::List&lt;dynamic&gt;&gt;'. compiler message: Try changing the type of the left hand side, or casting the right hand side to 'dart.async::FutureOr&lt;dart.core::List&lt;dynamic&gt;&gt;'. compiler message: return await rootBundle.loadString('assets/test.json'); compiler message: ^

标签: json dart flutter


【解决方案1】:

首先,导入服务包

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

然后,改变这个:

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

进入这个:

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

loadString() 方法返回一个字符串类型的 Future。

检查这里: https://docs.flutter.io/flutter/services/AssetBundle/loadString.html

【讨论】:

  • 谢谢。当我改成字符串时。 print(_data[0] [' title ']); 行得到这些错误 String can't be assigned to the parameter type int
  • 我在getQuakes();方法之后写的。
猜你喜欢
  • 2021-10-27
  • 2023-03-05
  • 2021-08-23
  • 2020-03-01
  • 2021-09-25
  • 2021-02-25
  • 2020-09-12
  • 2021-11-04
  • 1970-01-01
相关资源
最近更新 更多