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

我是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,child: Text(
                                              'Availability : ${product[i]['price']}',Align(
                                              child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,children: <Widget>[
                                              Column(
                                                children: <Widget>[
                                                  Text(
                                                    'Rs. : ${product[i]['price']}',style: TextStyle(
                                                        fontSize: 15.0,color: Colors.red),)),Align(
                                            alignment: Alignment.center,child: Icon(
                                              Icons.favorite,color: Colors.deepPurple,size: 40.0,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",)
                                                  ],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}]
linwen86 回答:单击Flutter中的按钮时如何将对象存储在数组中?

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

import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:http/http.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(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then,without quitting the app,try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",// or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,),home: HelpScreen(),);
  }
}

class HelpScreen extends StatefulWidget {
  @override
  HelpScreenState createState() {
    return HelpScreenState();
  }
}

class HelpScreenState extends State<HelpScreen> {
  WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Help')),body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Container(
              height: 300,child: WebView(
                initialUrl: 'abc',javascriptMode: JavascriptMode.unrestricted,onWebViewCreated: (WebViewController webViewController) {
                  _controller = webViewController;
                  _loadHtmlFromString();
                },IconButton(
              icon: const Icon(
                Icons.thumb_up,semanticLabel: 'Thumbs up',onPressed: () {
                _loadHtmlFromString();
              },],);
  }

  _loadHtmlFromString() async {
    String fileText = '''
    <!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>
    ''';

    _controller.loadUrl( Uri.dataFromString(
        fileText,mimeType: 'text/html',encoding: Encoding.getByName('utf-8')
    ).toString());
  }
}

此处pID为字符串,但prefs.setStringList('id_list',pId); 希望将字符串列表作为第二个参数

,
_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');


  }

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

本文链接:https://www.f2er.com/3140130.html

大家都在问