skip to Main Content

When I learned that no file could be modified inside the assets folder I did the following:

  1. Use a variable to store data. How to call it again?
  2. Using SQLite shows the same problem and error messages.
  3. Store the data and call it from a text file, but it is also useless.

Error messages:

  • Sometimes the application hangs during the build phase at this line in the terminal:

    Connecting to VM Service at ws://127.0.0.1

  • Using getApplicationDocumentsDirectory either with a JSON file or SQLite:

    Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)

  • Trying to store or read from text file:

    Unsupported operation: _Namespace

My attempts:

{ 
    "user" :[
    {
        "name":"sife",
        "age":44
    },
    {
        "name":"hasan",
        "age":22
    }
]
}

I want to add this:

"name":"faris",
"age":30

I want an example that can be applied with the lowest specifications and the least libraries and complexity.

2

Answers


  1. Chosen as BEST ANSWER

    I used Mr. Naqib's intervention and asked the artificial intelligence site to merge what the professor wrote with what I want specifically, so the result was as follows.

    import 'dart:convert';
    import 'dart:io';
    
    import 'package:flutter/material.dart';
    import 'package:path_provider/path_provider.dart';
    
    class UserList {
      List<User> userList;
    
      UserList({required this.userList});
    
      factory UserList.fromJson(Map<String, dynamic> json) {
        var userList = json['user'] as List;
        List<User> users = userList.map((userJson) => User.fromJson(userJson)).toList();
        return UserList(userList: users);
      }
    
      Map<String, dynamic> toJson() {
        return {
          'user': userList.map((user) => user.toJson()).toList(),
        };
      }
    }
    
    class User {
      String name;
      int age;
    
      User({required this.name, required this.age});
    
      factory User.fromJson(Map<String, dynamic> json) {
        return User(
          name: json['name'],
          age: json['age'],
        );
      }
    
      Map<String, dynamic> toJson() {
        return {
          'name': name,
          'age': age,
        };
      }
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      List<User> userList = [];
    
      void _saveData() async {
        // Create a UserList object and add the current list of users
        UserList userListObject = UserList(userList: userList);
    
        // Convert the UserList object to a JSON object
        Map<String, dynamic> json = userListObject.toJson();
    
        // Get the directory where the file should be saved
        final directory = await getApplicationDocumentsDirectory();
    
        // Create the file
        final file = File('${directory.path}/users.json');
    
        // Write the JSON data to the file
        file.writeAsStringSync(jsonEncode(json));
    
        // Show a snackbar to indicate that the data has been saved
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Data saved successfully'),
          ),
        );
      }
    
      void _showData() async {
        // Get the directory where the file is saved
        final directory = await getApplicationDocumentsDirectory();
    
        // Open the file
        final file = File('${directory.path}/users.json');
    
        if (!file.existsSync()) {
          // Show a snackbar to indicate that the file doesn't exist
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('No data found'),
            ),
          );
          return;
        }
    
        // Read the JSON data from the file
        String jsonString = await file.readAsString();
    
        // Convert the JSON data to a UserList object
        Map<String, dynamic> json = jsonDecode(jsonString);
        UserList userListObject = UserList.fromJson(json);
    
        // Update the list of users
        setState(() {
          userList = userListObject.userList;
        });
      }
    
      void _addUser() {
        // Create a new User object and add it to the list of users
        User user = User(name: 'New User', age: 0);
        setState(() {
          userList.add(user);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('User List'),
            ),
            body: Column(
              children: [
                Expanded(
                  child: ListView.builder(
                    itemCount: userList.length,
                    itemBuilder: (context, index) {
                      final user = userList[index];
                      return ListTile(
                        title: Text(user.name),
                        subtitle: Text('Age: ${user.age}'),
                      );
                    },
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    ElevatedButton(
                      onPressed: _saveData,
                      child: Text('Save'),
                    ),
                    ElevatedButton(
                      onPressed: _showData,
                      child: Text('Show Data'),
                    ),
                    ElevatedButton(
                      onPressed: _addUser,
                      child: Text('Add User'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      }
    }
    
    void main() {
      runApp(MyApp());
    }
    

  2. Here is a sample example, if you want me to explain this, feel free to comment and ask for explanation

    class UserList {
      List<User> userList;
    
      UserList({required this.userList});
    
      factory UserList.fromJson(Map<String, dynamic> json) {
        var userList = json['user'] as List;
        List<User> users = userList.map((userJson) => User.fromJson(userJson)).toList();
        return UserList(userList: users);
      }
    
      Map<String, dynamic> toJson() {
        return {
          'user': userList.map((user) => user.toJson()).toList(),
        };
      }
    }
    
    class User {
      String name;
      int age;
    
      User({required this.name, required this.age});
    
      factory User.fromJson(Map<String, dynamic> json) {
        return User(
          name: json['name'],
          age: json['age'],
        );
      }
    
      Map<String, dynamic> toJson() {
        return {
          'name': name,
          'age': age,
        };
      }
    }
    
    void main() {
    
      Map<String, dynamic> json = {
        "user": [
          {"name": "sife", "age": 44},
          {"name": "hasan", "age": 22}
        ]
      };
      UserList userList = UserList.fromJson(json);
    
      userList.userList.add(User(name: "faris", age: 30));
    
      Map<String, dynamic> updatedJson = userList.toJson();
      print(updatedJson);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search