如何在flutter应用程序中显示以共享首选项存储的json列表?

时间:2019-05-18 18:29:36

标签: android json flutter

我想从flutter应用程序的共享首选项中显示存储的JSON数据,然后在列表视图中显示它们或在flutter中显示文本。但失败并返回null。我已经将json存储在共享首选项中,并且它返回JSON,但是我无法将该json解码到列表视图中

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:kilimo_biashara1/Model/AccountInfo.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Accounts extends StatefulWidget {
  @override
  _AccountsState createState() => _AccountsState();
}

class _AccountsState extends State<Accounts> {

  Map profile;
  String data;
  SharedPreferences shared_User = await SharedPreferences.getInstance();
  data = shared_User.getString("user" ?? "");
  print(data);
  profile = json.decode(data);
  print(profile);
}

  @override
  void initState() {
    super.initState();
    this.getProfile();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Card(
        child: Column(
          children: <Widget>[
            Text(data["name"]),
            //Text(data.name),
          ],
        ),
      ),
    );
  }

}

错误消息:

The following NoSuchMethodError was thrown building Accounts(dirty, state: _AccountsState#23ebf):
I/flutter (22728): The method '[]' was called on null.
I/flutter (22728): Receiver: null
I/flutter (22728): Tried calling: []("name")
I/flutter (22728): When the exception was thrown, this was the stack:
I/flutter (22728): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5)
I/flutter (22728): #1      _AccountsState.build (package:kilimo_biashara1/CustomerInfo/Account.dart:39:17)
I/flutter (22728): #2      StatefulElement.build (package:flutter/src/widgets/framework.dart:3825:27)
I/flutter (22728): #3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3739:15)
I/flutter (22728): #4      Element.rebuild (package:flutter/src/widgets/framework.dart:3565:5)
I/flutter (22728): #5      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3722:5)
I/flutter (22728): #6      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3864:11)
I/flutter (22728): #7      ComponentElement.mount (package:flutter/src/widgets/framework.dart:3717:5)
I/flutter (22728): #8      Element.inflateWidget (package:flutter/src/widgets/framework.dart:2961:14)
I/flutter (22728): #9      Element.updateChild (package:flutter/src/widgets/framework.dart:2764:12)
I/flutter (22728): #10     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart

3 个答案:

答案 0 :(得分:0)

我假设shared_UsergetProfile函数中。

应将profile=json.decode(data);行包裹在setState中,以通知框架它需要更新UI,如下所示:

setState(() {
profile=json.decode(data);
});

文本应为Text(profile["name"] ?? ""),而不是Text(data["name"]),。 然后您应该初始化配置文件映射-Map profile = {};

答案 1 :(得分:0)

我认为这是您所需要的:

import 'dart:convert';

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

SharedPreferences preferences;

final String sampleJson = '{ "name":"John", "age":30, "car":null }';

void main() async {
  preferences = await SharedPreferences.getInstance();
  await preferences.setString('test', sampleJson);
  runApp(App());
}

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  var data;

  @override
  void initState() {
    data = jsonDecode(preferences.getString('test'));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: Text(data.toString()),
        ),
      ),
    );
  }
}

此外,您可以复制此逻辑:

Load and read data from Json file

答案 2 :(得分:0)

这个问题的主要问题是如何序列化和反序列化字符串JSON数据,以使Flutter应用程序数据结构可以读取。 示例检查此代码:

检查此代码

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:kilimo_biashara2/Model/AccountInfo.dart';
import 'package:kilimo_biashara2/Registration/Login.dart';
class Accounts extends StatefulWidget {
  @override
  _AccountsState createState() => _AccountsState();
}
class _AccountsState extends State<Accounts> {

  var messages =const [];
  String profile;
  Future getProfile() async{
        SharedPreferences shared_User = await SharedPreferences.getInstance();
        profile =shared_User.getString("user");//getting stored json data from sharedpreference
        print(profile);//print the json string results
       List collection=json.decode(profile);//decode json data
        print(collection);//debug print data
       List<Profile> _messages =collection.map((json) => Profile.fromJson(json)).
           toList();// map json data to list 
        print(_messages);//print list data from json data
      setState(() {
        messages =_messages;
      });

  }
  @override
  void initState() {
    // TODO: implement initState
    getProfile();
    super.initState();

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
body:ListView.separated(
    itemBuilder:(BuildContext context,int index){
      Profile prof=messages[index];// initialize class of data model
      return Card(
        child:new Column(
          children: <Widget>[
            Container(
              height: 250.0,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16.0),
                shape: BoxShape.rectangle,
                image: DecorationImage(
                  image: NetworkImage(
                    "${prof.prof_url}",///returned data from json
                  ),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          new  ListTile(
              title: Text(prof.name),//returned data from json
              leading: new Icon(Icons.account_box,color: Colors.blue,size: 26.6,),
            ),
            new Divider(color: Colors.green,indent: 16.0,),
          new  ListTile(
            title: Text(prof.email),//returned data from json
            leading: new Icon(Icons.email,color: Colors.blue,size: 26.6,),
          ),
          new Divider(color: Colors.green,indent: 16.0,),
          new  ListTile(
            title: Text("${prof.phone}"),// returned datta from json
            leading: new Icon(Icons.phone,color: Colors.blue,size: 26.6,),
          ),
            new Divider(color: Colors.green,indent: 16.0,),
          ],
        ),
      );

    } ,
    separatorBuilder: (context,index)=>Divider(),
     itemCount: messages.length),
    );
  }
}

还在制作了UI和主dart文件之后,然后制作了一个数据模型类,该类将把数据从json转换为list并被访问到main。飞镖文件 检查以下代码:

class Profile{
  final int phone;
  final String name;
  final String prof_url;
  final String email;
  Profile(this.phone, this.name, this.prof_url, this.email);
  Profile.fromJson(Map<String, dynamic> json):
        phone =  json['phone'],
        name = json['name'],
        prof_url = json['prof_url'],
        email= json['email'];
}

完成此代码后,您将能够将JSON数据从共享首选项传递到列表视图

NB 必须知道如何序列化和反序列化JSON数据