flutter - 单击Flutter中的按钮时如何将对象存储在数组中?

标签 flutter dart

我是Flutter的新手。我想单击按钮时将所有id存储在数组中。如果可以的话请给我一个解决方案,然后我接受您的回答这里有人为此提供解决方案吗?提前致谢。这是我的代码。

错误的样子,

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'String' is not a subtype of type 'List<String>'

码:
_saveQtyValue(id) async {
    print(id);
    var pId = id; // 5d9890c7773be00ab5b41701


    final prefs = await SharedPreferences.getInstance();
    prefs.setStringList('id_list', pId);

    List<String> show_id = List<String>();
    show_id = prefs.getStringList('id_list');
    print('id====$show_id');

    List<String> list = show_id;
    list.add(id);
    print('list id=====$list');


  }

在单击_saveQtyValue()函数传递ID时,我要将所有ID存储在一个数组中。

完整代码:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
import 'package:spurtcommerce/config.dart' as config;
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

class ProductViewScreen extends StatefulWidget {
  final id;
  final name;
  ProductViewScreen({Key key, @required this.id, this.name}) : super(key: key);
  @override
  ProductViewScreenState createState() => ProductViewScreenState();
}

class ProductViewScreenState extends State<ProductViewScreen> {
  List product;
  List productImage;
  List pId;

  // List<String> productIdArray = new List();

  @override
  void initState() {
    super.initState();
    this.getProduct(); // Function for get product details
  }

/*
 *  For Product get by id
 */
  Future<String> getProduct() async {
    var id = this.widget.id;
    var response = await http.get(
        Uri.encodeFull(config.baseUrl + 'product-store/productdetail/$id'),
        headers: {"Accept": "application/json"});
    setState(() {
      product = json.decode(response.body)['data'];
    });

    setState(() {
      productImage = product[0]['productImage'];
    });

    return "Successfull";
  }

  _saveQtyValue(id) async {
    print(id);
    // var pId = id;
    setState(() {
      pId = id;
    });
  print('state id===$pId');
    final prefs = await SharedPreferences.getInstance();
    prefs.setStringList('id_list', pId);

    List<String> show_id = List<String>();
    show_id = prefs.getStringList('id_list');
    print('id====$show_id');

    List<String> list = show_id;
    list.add(id);
    print('list id=====$list');

    Toast.show("Added in cart", context,
        duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(this.widget.name),
          actions: [
            Icon(
              Icons.notifications,
              color: Colors.yellowAccent,
              size: 24.0,
            ),
          ],
        ),
        body: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Column(
              children: <Widget>[
                Column(children: [
                  CarouselSlider(
                    height: 200.0,
                    items: productImage.map((i) {
                      return Builder(
                        builder: (BuildContext context) {
                          return Container(
                              margin: EdgeInsets.symmetric(horizontal: 5.0),
                              child: Image.network(
                                  config.mediaUrl +
                                      '${i['containerName']}' +
                                      '${i['image']}',
                                  width: 200,
                                  height: 200,
                                  fit: BoxFit.fill));
                        },
                      );
                    }).toList(),
                  ),
                ]),
                new Row(children: <Widget>[
                  Expanded(
                    child: SizedBox(
                        height: 700.0,
                        child: new ListView.builder(
                          itemCount: product.length,
                          itemBuilder: (BuildContext ctxt, int i) {
                            return SizedBox(
                              child: Card(
                                color: Colors.grey[200],
                                child: Padding(
                                  padding:
                                      EdgeInsets.only(right: 5.0, left: 5.0),
                                  child: new Container(
                                      margin: EdgeInsets.all(10),
                                      child: Column(
                                        children: <Widget>[
                                          Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              '${product[i]['name']}',
                                              textAlign: TextAlign.left,
                                              style: TextStyle(fontSize: 15.0),
                                            ),
                                          ),
                                          new Divider(),
                                          Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              'Category: ${product[i]['Category'][0]['categoryName']}',
                                              textAlign: TextAlign.right,
                                              style: TextStyle(fontSize: 15.0),
                                            ),
                                          ),
                                          new Divider(),
                                          Align(
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              'Availability : ${product[i]['price']}',
                                              textAlign: TextAlign.right,
                                              style: TextStyle(fontSize: 15.0),
                                            ),
                                          ),
                                          new Divider(),
                                          Align(
                                              child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: <Widget>[
                                              Column(
                                                children: <Widget>[
                                                  Text(
                                                    'Rs. : ${product[i]['price']}',
                                                    textAlign: TextAlign.right,
                                                    style: TextStyle(
                                                        fontSize: 15.0,
                                                        color: Colors.red),
                                                  ),
                                                ],
                                              ),
                                            ],
                                          )),
                                          new Divider(),
                                          Align(
                                            alignment: Alignment.center,
                                            child: Icon(
                                              Icons.favorite,
                                              color: Colors.deepPurple,
                                              size: 40.0,
                                            ),
                                          ),
                                          new Divider(),
                                          Align(
                                            child: Card(
                                              child: FlatButton(
                                                onPressed: () => {
                                                  _saveQtyValue(
                                                      '${product[i]['productId']}')
                                                },
                                                color: Color.fromRGBO(
                                                    94, 199, 182, 0.9),
                                                padding: EdgeInsets.all(10.0),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.center,
                                                  children: <Widget>[
                                                    Icon(Icons.shopping_cart),
                                                    Text(
                                                      "   Add to Cart",
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ),
                                          ),
                                          new Divider(),
                                          Align(
                                            alignment: Alignment.topLeft,
                                            child: Text(
                                              'Description',
                                              style: TextStyle(
                                                  fontSize: 15,
                                                  fontWeight: FontWeight.bold),
                                            ),
                                          ),
                                          Align(
                                              alignment: Alignment.center,
                                              child: Html(
                                                data:
                                                    '${product[i]['description']}',
                                              )),
                                        ],
                                      )),
                                ),
                              ),
                            );
                          },
                        )),
                  ),
                ]),
              ],
            )));
  }
}

我想要这种格式
[{5d9890c7773be00ab5b41701},{5d9890c7773be00ab5b41702}]

最佳答案

_saveQtyValue(id) async {
    print(id);
    var pId = id; // 5d9890c7773be00ab5b41701


    final prefs = await SharedPreferences.getInstance();

    List<String> show_id = prefs.getStringList('id_list') ?? List<String>();  // <-EDITED HERE
    print('id====$show_id');

    List<String> list = show_id;
    list.add(id);
    prefs.setStringList('id_list', list);

    print('list id=====$list');


  }

我对您的函数进行了较小的编辑,这应该保存字符串列表。该代码可以通过其他方式进行改进。

关于flutter - 单击Flutter中的按钮时如何将对象存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58760834/

相关文章:

firebase - 为什么我的 flutter 应用程序在我的设备离线时在 firestore 上保存了两次?

flutter - 在setState上更新UI时出现 flutter 问题

flutter - BLoC产生新状态后未更新BlocBuilder()

dart - Polymer Dart、全局变量和数据绑定(bind)(可观察)

flutter - 类型 'TextEditingController' 不是类型转换中类型 'int' 的子类型

android - Flutter ImagePicker 错误 "attribute android:requestLegacyExternalStorage not found"

android - 在 Flutter 中实现视频提要的最佳方式是什么?

mongodb - 如何将 Flutter 与 MongoDB 连接

flutter - 在 SingleChildScrollView 中实现嵌套 ListView

android - flutter :引发了另一个异常:类型 'Future<dynamic>' 不是类型 'String' 的子类型