在JSON文件中保存数据所需的代码,即写入并添加

erhoui1w  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(97)

我想要的只是在JSON文件中保存数据所需的代码,即写入并添加它,而不是阅读它。我成功了。另外,我想询问是否可以在应用程序实际运行时立即添加数据,或者仅在应用程序关闭时添加数据?
连接到JSON文件有几种方法吗?还是只有一种方法?!!wait getApplicationDocumentsDirectory();
最后,我将把完整的代码给你,并向你展示错误消息第一个错误消息出现时,上传数据按钮按下Error loading users: Expected a value of type 'List<dynamic>', but got one of type '_JsonMap'
尝试保存数据时出现第二条错误消息:Error saving users: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<User> _users = [];

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

// TO load data from site.json file.
  Future<void> _loadUsers() async {
    try {
      final jsonString = await rootBundle.loadString('assets/site.json');
      final List<dynamic> jsonList =json.decode(jsonString) as List;
      setState(() {
        _users = jsonList.map((json) => User.fromJson(json)).toList();
      
      });
    } catch (e) {
      print('Error loading users: ${e.toString()}');
    }
  }
 
 // TO save data when add new data to site.json file.
  Future<void> _saveUsers() async {
    try {
      final jsonString = json.encode(_users);
      final file = await _getLocalFile();
      await file.writeAsString(jsonString);
      print('Users saved successfully');
    } catch (e) {
      print('Error saving users: ${e.toString()}');
    }
  }

  Future<File> _getLocalFile() async {
    final directory = await getApplicationDocumentsDirectory();
    return File('${directory.path}assets/site.json');
  }

  void _addUser() {
    setState(() {
      _users.add(User(name: 'John', age: 30));
    });
  }

  void _clearUsers() {
    setState(() {
      _users.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
           ElevatedButton(
              onPressed: _loadUsers,
              child: Text('Load Users'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _saveUsers,
              child: Text('Save Users'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _addUser,
              child: Text('Add User'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _clearUsers,
              child: Text('Clear Users'),
            ),
            SizedBox(height: 20),
            Text('Users:'),
            Expanded(
              child: ListView.builder(
                itemCount: _users.length,
                itemBuilder: (context, index) {
                  final user = _users[index];
                  return ListTile(
                    title: Text(user.name),
                    subtitle: Text('${user.age} years old'),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class User {
  final String name;
  final int age;

  User({required this.name, required this.age});

  factory User.fromJson(Map<String, dynamic> json) =>
      User(name: json['name'], age: json['age']);

  Map<String, dynamic> toJson() => {'name': name, 'age': age};
}

字符串

kq4fsx7k

kq4fsx7k1#

在将json.decode赋值给变量类型之前,可以打印runtimeType和列表本身,

//DONT DO: final List<dynamic> jsonList =json.decode(jsonString) as List;

 //DO: final dynamic jsonData = json.decode(jsonString);
 log(jsonData.runtimeType)
 log(jsonData)

字符串

相关问题