2
  • I have a Json file having some user data as an array , I am able to read those data in my flutter project , But what I wanna do is to add some other user from the data I receive from the textfield in my flutter app.

  • Can anyone tell me how to do that ? Thanks in advance.

My Json file looks something like this.

    {
    "users": [
        {
            "id": 1,
            "username": "steve",
            "password": "captainamerica"
        }
     ]
    }

and I have to add another user with id - 2, username - tony, and password - ironman.

7
  • how you get the json data? Commented Dec 11, 2019 at 6:08
  • @JohnJoe I'm getting the json data using the jsonDecode() function in dart:convert library Commented Dec 11, 2019 at 6:29
  • you want to submit data to server? Commented Dec 11, 2019 at 6:31
  • @daringdk do you have an object class for your JSON? Commented Dec 11, 2019 at 6:32
  • 1
    oh, sorry; corrected. Commented Dec 11, 2019 at 6:33

1 Answer 1

6

I have tried showing you how to map the JSON to OBJECT and then add a new user to the users object and then to JSON again.

Here's the complete code:

If you have any doubts, please ask:

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

UsersPodo _usersPodo; // Users object to store users from json

// A function that converts a response body into a UsersPodo
UsersPodo parseJson(String responseBody) {
  final parsed = json.decode(responseBody);
  return UsersPodo.fromJson(parsed);
}

class Demo extends StatefulWidget {
  @override
  _Demo createState() => _Demo();
}

class _Demo extends State<Demo> {
  final String localJson = '''
  {
    "users": [
        {
            "id": 1,
            "username": "steve",
            "password": "captainamerica"
        }
    ]
}'''; // local json string

  Future<UsersPodo> fetchJSON() async {
    return compute(parseJson, localJson);
  }

  Widget body() {
    return FutureBuilder<UsersPodo>(
      future: fetchJSON(),
      builder: (context, snapshot) {
        return snapshot.hasError
            ? Center(child: Text(snapshot.error.toString()))
            : snapshot.hasData
                ? _buildBody(usersList: snapshot.data)
                : Center(child: Text("Loading"));
      },
    );
  }

  Widget _buildBody({UsersPodo usersList}) {
    _usersPodo = usersList;

    _usersPodo.users.add(new Users(id: 1, username: "omishah", password: "somepassword")); // add new user to users array

    return Text(_usersPodo.users[1].toJson().toString()); // just for the demo output

    // use _usersPodo.toJson() to convert the users object to json
  }

  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xfff3f3f3),
        appBar: AppBar(backgroundColor: Colors.red[900], title: Text("DEMO")),
        body: body());
  }
}

// PODO Object class for the JSON mapping
class UsersPodo {
  List<Users> users;

  UsersPodo({this.users});

  UsersPodo.fromJson(Map<String, dynamic> json) {
    if (json['users'] != null) {
      users = new List<Users>();
      json['users'].forEach((v) {
        users.add(new Users.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.users != null) {
      data['users'] = this.users.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Users {
  int id;
  String username;
  String password;

  Users({this.id, this.username, this.password});

  Users.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    username = json['username'];
    password = json['password'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['username'] = this.username;
    data['password'] = this.password;
    return data;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Suppose the JSON is saved on disk, to add a User to the file I have to parse the whole file, add the user and rewrite the whole file or is there a nonlinear constant approach to append to the file but keeping the json format?
@UmbertoFontanazza sadly, no.

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.