从资产文件夹中的JSON文件而非URL中获取数据

时间:2020-06-25 17:14:45

标签: json flutter dart

以下代码是从url提取数据的,我想将其更改为从资产文件夹中提取数据。

我是Flutter的新手,请帮助。如何将json文件放在本地而不是url。

我无法考虑应对以下代码进行哪些更改以使其起作用。

我试图修复它,但我不能,如果有人可以提供帮助,我会感激不尽。

这是我的代码:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'user.dart';

void main() {
  runApp(new MaterialApp(home: HomePage()));
}
class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => HomePageState();
}

List data;
List<User> userlist = List();
List<User> usersavedlist = List();
int index;

class HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'UserList Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('UserList Flutter'),
          actions: <Widget>[
            IconButton(icon: const Icon(Icons.list), onPressed: _pushSaved),
          ],
        ),
        body: listView(),
      ),
    );
  }

  Future<String> fetchData() async {
    final url =
        'https://raw.githubusercontent.com/highmobdevelopment/userlist/master/contacts.json';
    final response = await http.get(url);

    if (response.statusCode == 200) {
      print('succesfull parse');

      this.setState(() {
        data = json.decode(response.body);
        data.forEach((element) => userlist.add(new User.fromJson(element)));
      });
    }

    return "Success!";
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  listView() {
    return ListView.builder(
      itemCount: userlist == null ? 0 : userlist.length,
      itemBuilder: (context, index) {
        return Column(
          children: <Widget>[_buildRow(index, userlist), const Divider()],
        );
      },
    );
  }

  Widget _buildRow(index, userlist) {
    final bool alreadySaved = usersavedlist.contains(userlist[index]);

    return ListTile(
      title: Text(
        userlist[index].name

寻求支持,请解决此问题。

2 个答案:

答案 0 :(得分:0)

首先,您需要在pubspec.yaml文件中声明json文件。

assets:
    - assets/contacts.json

我不确定,但是您的fetchData()方法必须更改为类似的内容

    Future<String> fetchData() async {
        String data = await 
        DefaultAssetBundle.of(context).loadString("assets/contacts.json");
        
       final jsonResult = json.decode(data);
       
       this.setState(() {
            jsonResult.forEach((element) => userlist.add(new User.fromJson(element)));
       });
  
    
      return "Success!";
  }

更新:尝试以下完整示例:

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

class JsonFromAsset extends StatefulWidget {
  @override
  _JsonFromAssetState createState() => _JsonFromAssetState();
}

class _JsonFromAssetState extends State<JsonFromAsset> {
  List<User> userlist = [];

  Future<String> fetchData() async {
    String data =
        await DefaultAssetBundle.of(context).loadString("assets/contacts.json");

    final jsonResult = json.decode(data);

    this.setState(() {
      jsonResult.forEach((element) => userlist.add(new User.fromJson(element)));
    });

    return "Success!";
  }

  @override
  Widget build(BuildContext context) {
    fetchData();
    return Scaffold(
        body: Container(
            child: userlist.length > 0
                ? ListView.builder(
                    itemCount: userlist == null ? 0 : userlist.length,
                    itemBuilder: (context, index) {
                      return Container(child: Text(userlist[index].firstName));
                    },
                  )
                : Center(child: Text('empty'))));
  }
}

答案 1 :(得分:0)

您可以使用flutters服务来加载JSON字符串。使用以下代码。

    import 'package:flutter/services.dart' show rootBundle;
    import 'dart:convert' as convert;
    
//For Local JSON File
    loadJsonData()async{
    var rawString= await rootBundle.loadString('assets/config.json');
    var jsonData= convert.jsonDecode(rawString);              
    }

//for Remote JSON File

     Future<String> fetchData() async {
     final url ='https://raw.githubusercontent.com/highmobdevelopment/userlist/master/contacts.json';
        final response = await http.get(url,headers: {"Accept": "application/json"});
    
        if (response.statusCode == 200) {
          setState(() {
             data = convert.jsonDecode(response.body);
             data.forEach((element) => userlist.add(new User.fromJson(element)));
          });
        }
    
        return "Success!";
      }