简体   繁体   English

将数据从一个屏幕发送到另一屏幕抖动

[英]send data from one screen to another screen flutter

I am trying to pass data from one screen to another screen. 我正在尝试将数据从一个屏幕传递到另一屏幕。

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

By using the above code I am trying to send data but I am facing issue like type 'List' is not a subtype of type 'SubCategoryData' in type cast" 通过使用上面的代码,我试图发送数据,但是我遇到的问题是类型“列表”不是类型转换中类型“ SubCategoryData”的子类型。

got an error and even I am not getting how to send data with an index value.Please let me know. 出现错误,甚至我都没有如何使用索引值发送数据。请让我知道。

Below is my ChewieDemo class: Here I am trying to receive the data from another class. 下面是我的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,
    );
  }

This is the model class of SubCategoryData. 这是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';
      }
    }

1. Add the dependency 1.添加依赖项

Before starting, you need to add the shared_preferences plugin to the pubspec.yaml file: 在开始之前,您需要将shared_preferences插件添加到pubspec.yaml文件中:

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

2. Save data 2.保存数据

To persist data, use the setter methods provided by the SharedPreferences class. 要保留数据,请使用SharedPreferences类提供的setter方法。 Setter methods are available for various primitive types, such as setInt, setBool, and setString. Setter方法可用于各种原始类型,例如setInt,setBool和setString。

Setter methods do two things: First, synchronously update the key-value pair in-memory. 设置器方法有两件事:第一,同步更新内存中的键值对。 Then, persist the data to disk. 然后,将数据持久保存到磁盘。

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

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

3. Read data 3.读取数据

To read data, use the appropriate getter method provided by the SharedPreferences class. 要读取数据,请使用SharedPreferences类提供的适当的getter方法。 For each setter there is a corresponding getter. 对于每个设置器,都有一个对应的getter。 For example, you can use the getInt, getBool, and getString methods. 例如,可以使用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 data 4.删除数据

To delete data, use the remove method. 要删除数据,请使用remove方法。

content_copy
final prefs = await SharedPreferences.getInstance();

prefs.remove('counter');

you are getting a list of SubCategoryData from the httpcall . 你得到的名单SubCategoryDatahttpcall If you need to pass a List of your SubCategoryData model you need first to fix the following in your ChewieDemo class 如果你需要传递一个List您的SubCategoryData模型,你需要首先解决在以下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();
  }
}

and when you push the following: 当您按下以下命令时:

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

where categoryNames is a List<SubCategoryData> 其中categoryNames是一个List<SubCategoryData>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM