Search code examples
flutterdartsharedpreferences

Store List<Obj> to SharedPreferences


I want to store List<WorkForceArguments> to SharedPreferences.

import 'dart:convert';
 
class WorkForceArguments {
  var name;
  var no;
  WorkForceArguments({this.name, this.no});
 
  factory WorkForceArguments.fromJson(String str) =>
      WorkForceArguments.fromMap(json.decode(str));
 
  String toJson() => json.encode(toMap());
 
  factory WorkForceArguments.fromMap(Map<String, dynamic> json) =>
      WorkForceArguments(
        name: json["name"],
        no: json["no"],
      );
 
  Map<String, dynamic> toMap() => {
        "name": name,
        "no": no,
      };
}
 

In pageB, when submit button is clicked, it will pop the data back to page A

 Widget _showButton() {
    return Container(
      width: double.infinity,
      height: 40,
      child: MaterialButton(
        color: Theme.of(context).primaryColor,
        onPressed: () {
          Navigator.pop(
              context,
              WorkForceArguments(
                  _workForceController.text, _numberController.text));  // Error!
        },
        child: Text(
          Localization.of(context).submit,
          style: TextStyle(fontSize: 15.0, color: Colors.white),
        ),
      ),
    );
  }

And in page A, it has a store button to store data to SharedPreferences. But I get error on PageB.

  Navigator.pop(
                  context,
                  WorkForceArguments(
                      _workForceController.text, _numberController.text));  // Error too many arguments, expect 0 but found 2

Solution

  •  Navigator.pop(
      context,
      WorkForceArguments(
        name: _workForceController.text,
        no: _numberController.text,
      ),
    )
    

    You tried to add arguments to constructor with named parameters, read more about arguments to constructors and methods in Dart here.