颤振如何在共享首选项中存储int列表

时间:2020-02-14 04:56:24

标签: flutter dart sharedpreferences flutter-layout flutter-dependencies

在这里,我想以共享首选项存储产品的所有ID。但是在这里,当我使用setInt存储ID时,它将仅存储一个ID并删除以前的ID,因此我希望所有ID必须存储在共享首选项中,以及如何获取所有存储在共享首选项中的ID。

这是我尝试过的代码

 unAuthAddCart(dynamic itemId) async {
    try {
      SharedPreferences pref = await SharedPreferences.getInstance();
      var unAuthItemId = pref.setInt('unAuthItemid', itemId);
      print(unAuthItemId);
      var abc = pref.getInt('unAuthItemid');
      print("UnAuth Itme Id $abc");

    } catch (e) {
      print(e);
      print("Something went Wrong in Particular Product Cart");
    }
  }

2 个答案:

答案 0 :(得分:4)

您可以在下面复制粘贴运行完整代码
你可以
步骤1:将List<int>转换为List<String>
步骤2:使用prefs.setStringList保存
步骤3:使用prefs.getStringList取回
步骤4:隐瞒List<int>

代码段

List<int> intProductListOriginal = [11, 22, 33, 44, 55];

  void _incrementCounter() async {
    List<String> strList = intProductListOriginal.map((i) => i.toString()).toList();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList("productList", strList);

    List<String> savedStrList = prefs.getStringList('productList');
    List<int> intProductList = savedStrList.map((i) => int.parse(i)).toList();

    print("${intProductList.toString()}");

输出

I/flutter ( 4347): [11, 22, 33, 44, 55]

完整代码

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      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;
  List<int> intProductListOriginal = [11, 22, 33, 44, 55];

  void _incrementCounter() async {
    List<String> strList = intProductListOriginal.map((i) => i.toString()).toList();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setStringList("productList", strList);

    List<String> savedStrList = prefs.getStringList('productList');
    List<int> intProductList = savedStrList.map((i) => int.parse(i)).toList();

    print("${intProductList.toString()}");

    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),
      ),
    );
  }
}

答案 1 :(得分:2)

当前,没有任何选项可以直接将共享列表保存在Sharedpreferences中。您可以将字符串列表保存在sharedpreferences中。

这种情况最简单的方法是将 List 值转换为List 并存储它们。

此外,在检索时,您可以获取存储在共享首选项中的列表 ,并将其转换为原始列表

例如:

要将列表存储在共享首选项中。

SharedPreferences prefs=await SharedPreferences.getInstance();

// your custom int list
List<int> mList=[0,1,2,3,4];

// convert your custom list to string list
List<String> stringsList=  mList.map((i)=>i.toString()).toList();

// store your string list in shared prefs                
prefs.setStringList("stringList", stringsList);

要检索并将存储的字符串列表转换为原始的int列表

SharedPreferences prefs=await SharedPreferences.getInstance();

// fetch your string list      
List<String> mList = (prefs.getStringList('stringList') ?? List<String>());

//convert your string list to your original int list
List<int> mOriginaList = mList.map((i)=> int.parse(i)).toList();

print(mOriginaList);