Flutter 如何将从 rest API 接收到的每个键值保存到不同的共享偏好值,无论是字符串还是整数

Flutter how to save each key value receive from rest API to different shared preference value be it string or int

任何人都可以帮助我如何将这些对象数组保存在 flutter 的共享首选项中?我创建了一个 JSON rest API returns 下面的对象数组:

[{
    "first_name": "firstname",
    "last_name": "lastname",
    "profile_pic": "user.png",
    "designation_id": "33",
    "department_id": "2",
    "employee_id": "175",
    "level": "hr",
    "dept_code": "HR",
    "email": "email.com",
    "user_id": "1"
}]

我正在寻找有关如何将每个键值保存到共享首选项并重新使用它的解决方法。 例如保存 "first_name", "last_name"... 下面是如何接收我的 JSON:


final String baseUrl = "http://xxx/login.php";
    var response;
    Client client = Client();

Future<bool> createProfile(LoginProfile data) async {
      response = await client.post(
        "$baseUrl",
        headers: {"content-type": "application/json"},
        body: loginProfileToJson(data),
      );

    }

var resBody = json.decode(response.body); 
String array = resBody.toString(); 
SharedPreferences prefs = await SharedPreferences.getInstance(); 
prefs.setString('array', array);

通过以上,它不是单独接收值而是一起接收值,我想单独保存每个值以重用例如:

prefs.setString('firstname', first_name);
prefs.setString('lastname', last_name);
prefs.setString('level', level);
prefs.setString('deptcode', dept_code)... and so on.

您可以复制粘贴运行下面的完整代码
第 1 步:您可以将 Mapkeyvalue 传递给 Function setData
第二步:用jsonMap.forEach((k, v) => setData(k, v));做for循环
第 3 步:keyunderlinefirst_name 而不是 firstname ,但你可以在 setData 中删除 underline

代码片段

  setData(String k, String v) async {
     await prefs.setString(k, v);
  }

  void _incrementCounter() async {
    prefs = await SharedPreferences.getInstance();

    String jsonString = ...;

    var resBody = json.decode(jsonString);
    Map jsonMap = resBody[0];
    jsonMap.forEach((k, v) => setData(k, v));

    print(prefs.getString("first_name"));
    print(prefs.getString("dept_code"));

输出

I/flutter ( 6692): firstname
I/flutter ( 6692): HR

完整代码

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  SharedPreferences prefs;

  setData(String k, String v) async {
    await prefs.setString(k, v);
  }

  void _incrementCounter() async {
    prefs = await SharedPreferences.getInstance();

    String jsonString = '''
    [{
    "first_name": "firstname",
    "last_name": "lastname",
    "profile_pic": "user.png",
    "designation_id": "33",
    "department_id": "2",
    "employee_id": "175",
    "level": "hr",
    "dept_code": "HR",
    "email": "email.com",
    "user_id": "1"
}]
    ''';

    var resBody = json.decode(jsonString);
    Map jsonMap = resBody[0];
    jsonMap.forEach((k, v) => setData(k, v));

    print(prefs.getString("first_name"));
    print(prefs.getString("dept_code"));

    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

一个非常简单的解决方案是 运行 在您的地图上循环,您将得到 属性 和每个 key-value 对的名称,试试这个。

void main() {
  Map<String, dynamic> data = {
    "first_name": "firstname",
    "last_name": "lastname",
    "profile_pic": "user.png",
    "designation_id": "33",
    "department_id": "2",
    "employee_id": "175",
    "level": "hr",
    "dept_code": "HR",
    "email": "email.com",
    "user_id": "1"
};
  
  data.forEach((k, v) {
// set prefrence values here
 data.forEach((k, v) => print("Key : $k, Value : $v"));
});

}