首页 > 解决方案 > Flutter - 解析本地 JSON 的问题

问题描述

我正在使用这些关于如何解析本地 JSON 文件的说明( https://www.developerlibs.com/2018/11/flutter-how-to-parse-local-json-file-in.html )构建应用程序,但我遇到了错误消息。我仍然是 Flutter 的初学者,因此感谢您的帮助:

l/flutter ( 8377): The following NoSuchMethodError was thrown building FutureBuilder<String>(dirty, state: FutureBuilderState<String>#8f2a5):
l/flutter ( 8377): The method 'cast' was called on null.
l/flutter ( 8377): Receiver: null
l/flutter ( 8377): Tried calling: cast<Map<String, dynamic>>().

代码:

main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_load_local_json/country.dart';
import 'package:flutter_load_local_json/list.dart';

void main() {
  runApp(new MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: new ThemeData(
      primaryColor: const Color(0xFF02BB9F),
      primaryColorDark: const Color(0xFF167F67),
      accentColor: const Color(0xFF167F67),
    ),
    home: new MyApp(),
  ));
}

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

class MyAppState extends State<MyApp> {
  List data;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Load local JSON file",
          style: new TextStyle(color: Colors.white),),
        ),
        body: new Container(
          child: new Center(
            // Use future builder and DefaultAssetBundle to load the local JSON file
            child: new FutureBuilder(
                future: DefaultAssetBundle.of(context)
                    .loadString('assets/country.json'),
                builder: (context, snapshot) {
                  List<Country> countries =
                      parseJosn(snapshot.data.toString());
                  return !countries.isEmpty
                      ? new CountyList(country: countries)
                      : new Center(child: new CircularProgressIndicator());
                }),
          ),
        ));
  }

  List<Country> parseJosn(String response) {
    if(response==null){
      return [];
    }
    final parsed =
        json.decode(response.toString()).cast<Map<String, dynamic>>();
    return parsed.map<Country>((json) => new Country.fromJson(json)).toList();
  }
}

提前致谢

标签: flutter

解决方案


在解析 JSON 之前,您必须等待未来完成:

FutureBuilder(
  future: DefaultAssetBundle.of(context).loadString('assets/country.json'),                    
  builder: (context, snapshot) {
    if (snapshot.connectionState != ConnectionState.done) {
      return Text("Loading JSON...")
    }

    List<Country> countries = parseJson(snapshot.data.toString());
    return countries.isNotEmpty 
      ? new CountyList(country: countries)
      : new Center(child: Text("Empty list");
  }
),

更多信息:https ://api.flutter.dev/flutter/widgets/FutureBuilder-class.html 和https://flutter.dev/docs/development/data-and-backend/json


推荐阅读