【问题标题】:send data from one screen to another screen flutter将数据从一个屏幕发送到另一个屏幕颤动
【发布时间】:2019-07-18 15:26:36
【问题描述】:

我正在尝试将数据从一个屏幕传递到另一个屏幕。

List<SubCategoryData>categoryNames = new List<SubCategoryData>();
  List<String>categorieslist = [];
  bool isFirst=true;

  Future<SubCategoryModel>fetchCategories(BuildContext context) async {

    String url = "http://106.51.64.251:380/onnet_api/subcatListByCategory.php";

    var body = new Map<String,String>();
    body['publisherid']= 102.toString();
    body['tag'] = "category";
    body['subtag']= "list";
    body['parentId'] = 10.toString();

    http.Response res = await http.post(url,body: body);
    final categoryjsondata = json.decode(res.body);
    var map = Map<String,dynamic>.from(categoryjsondata);
    var categoryResponse = SubCategoryModel.fromJson(map);

    if(res.statusCode == 200){
      print('category Response: $categoryResponse');
      if(categoryResponse.status == 1){
        //final categoryModel = json.decode(res.body);
        var data = categoryjsondata['data']as List;
        print('category data: $data');

      /*  for(var model in categorieslist){
          categoryNames.add(new SubCategoryData.fromJson(model));
        }*/
    /*    SharedPreferences prefs = await SharedPreferences.getInstance();
        print("cat List Size: $categories");
        prefs.setStringList("categorylist", categories);*/
        Navigator.push(context, MaterialPageRoute(builder: (context)=> ChewieDemo(imageData: images[0],
            categoryData:data)));
      }
    }
  }

通过使用上面的代码,我正在尝试发送数据,但我遇到的问题是 type 'List' is not a subtype of type 'SubCategoryData' in type cast"

出错了,我什至没有知道如何发送带有索引值的数据。请告诉我。

下面是我的 ChewieDemo 课程: 这里我试图从另一个类接收数据。

class ChewieDemo extends StatefulWidget {

  final Datum imageData;
  final SubCategoryData categoryData;
  ChewieDemo({this.title = 'Player',Key key,@required this.imageData,@required this.categoryData}): super(key:key);
  final String title;

  @override
  State<StatefulWidget> createState() {
    return _ChewieDemoState();
  }
}

class _ChewieDemoState extends State<ChewieDemo> {

  TargetPlatform _platform;
  VideoPlayerController _videoPlayerController1;
  VideoPlayerController _videoPlayerController2;
  ChewieController _chewieController;

  @override
  void initState() {
    super.initState();
    print('url player :${widget.imageData.dataUrl}');
    print(widget.categoryData);
    // 'https://www.sample-videos.com/video123/mp4/480/big_buck_bunny_480p_20mb.mp4'
    _videoPlayerController1 = VideoPlayerController.network('${widget.imageData.dataUrl}');
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController1,
      aspectRatio: 3 / 2,
      autoPlay: true,
      looping: true,
      // Try playing around with some of these other options:

      // showControls: false,
      // materialProgressColors: ChewieProgressColors(
      //   playedColor: Colors.red,
      //   handleColor: Colors.blue,
      //   backgroundColor: Colors.grey,
      //   bufferedColor: Colors.lightGreen,
      // ),
      // placeholder: Container(
      //   color: Colors.grey,
      // ),
      // autoInitialize: true,
    );
  }

这是 SubCategoryData 的模型类。

class SubCategoryData {
      int id;
      int parentId;
      String name;
      int contentCount;
      String createdAt;
      int status;

      SubCategoryData({
        this.id,
        this.parentId,
        this.name,
        this.contentCount,
        this.createdAt,
        this.status,
      });

      factory SubCategoryData.fromJson(Map<String, dynamic> json) => new SubCategoryData(
        id: json["id"],
        parentId: json["parent_id"],
        name: json["name"],
        contentCount: json["content_count"],
        createdAt: json["createdAt"],
        status: json["status"],
      );

      Map<String, dynamic> toJson() => {
        "id": id,
        "parent_id": parentId,
        "name": name,
        "content_count": contentCount,
        "createdAt": createdAt,
        "status": status,
      };

      @override
      String toString() {
        // TODO: implement toString
        return '$id $parentId $name $contentCount';
      }
    }

【问题讨论】:

  • 你能把 ChewieDemo 类的代码展示一下吗?
  • 更新了我的问题。
  • 你不能使用:categoryData:(categoryData)as SubCategoryData) 因为categoryData是list类型,不能转换,什么是SubCategoryData类?显示它的代码
  • 它是一个模型类
  • 好的,如果您想显示模型类的代码,那么您无法将列表转换为此模型类的问题,以便我可以帮助您将列表中的数据填充到模型中类

标签: android ios flutter


【解决方案1】:

1.添加依赖

开始之前,需要将shared_preferences插件添加到pubspec.yaml文件中:

content_copy
dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "<newest version>"

2。保存数据

要持久化数据,请使用 SharedPreferences 类提供的 setter 方法。 Setter 方法可用于各种基本类型,例如 setInt、setBool 和 setString。

Setter 方法做了两件事:第一,同步更新内存中的键值对。然后,将数据持久化到磁盘。

// obtain shared preferences
final prefs = await SharedPreferences.getInstance();

// set value
prefs.setInt('counter', counter);

3.读取数据

要读取数据,请使用 SharedPreferences 类提供的适当的 getter 方法。每个 setter 都有一个对应的 getter。例如,您可以使用 getInt、getBool 和 getString 方法。

final prefs = await SharedPreferences.getInstance();

// Try reading data from the counter key. If it does not exist, return 0.
final counter = prefs.getInt('counter') ?? 0;

4.删除数据

要删除数据,请使用 remove 方法。

content_copy
final prefs = await SharedPreferences.getInstance();

prefs.remove('counter');

【讨论】:

  • 我要存储列表
【解决方案2】:

您将从httpcall 获得SubCategoryData 的列表。如果您需要传递您的 SubCategoryData 模型的 List,您需要首先在您的 ChewieDemo 类中修复以下问题

class ChewieDemo extends StatefulWidget {

  final Datum imageData;
  final List<SubCategoryData> categoryData;
  ChewieDemo({this.title = 'Player',Key key,@required this.imageData,@required this.categoryData}): super(key:key);
  final String title;

  @override
  State<StatefulWidget> createState() {
    return _ChewieDemoState();
  }
}

当你推送以下内容时:

      var categoryData = categoryjsondata['data'] as List;
      print('category data: $categoryData');

      for(var model in categoryData){
        categoryNames.add(new SubCategoryData.fromJson(model));
      }
      print("cat List Size: $categoryData");
      Navigator.push(context, MaterialPageRoute(builder: (context)=> ChewieDemo(imageData: null, categoryData: categoryNames));

其中 categoryNames 是 List&lt;SubCategoryData&gt;

【讨论】:

  • 我也试过了,但仍然面临同样的问题,例如类型 'List' is not a subtype of type 'List'
  • 我回答了你的新问题
猜你喜欢
  • 2023-01-11
  • 2021-09-30
  • 2021-11-07
  • 1970-01-01
  • 2019-05-10
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多