滚动后如何保持小部件的状态? [英] how to keep the state of my widgets after scrolling?

查看:81
本文介绍了滚动后如何保持小部件的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用杂乱的代码编写应用程序,我在开发中遇到了问题.我正在尝试使用带有自定义小部件的listview,它具有一个喜欢的图标,代表您喜欢它的产品.我在构造函数上传递了一个布尔值,以设置一个控制图标是完整还是空的变量.当我单击它时,我会更改它的状态.它的效果很棒,但是当我上下滚动时,它会丢失最新状态并返回到初始状态. 您知道滚动后如何保持状态吗?

I'm codeing an app with flutter an i'm haveing problems with the development. I'm trying to have a listview with a custom widget that it has a favourite icon that represents that you have liked it product. I pass a boolean on the constructor to set a variables that controls if the icons is full or empty. When i click on it i change it state. It works awesome but when i scroll down and up again it loses the lastest state and returns to the initial state. Do you know how to keep it states after scrolling?

要很多< 3

这是我的代码:

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new ListView.builder(
        itemCount: 100,
        itemBuilder: (BuildContext context, int index){
          return new LikeClass(liked: false);
        },
      ),
    );
  }
}

class LikeClass extends StatefulWidget {
  final bool liked;//i want this variable controls how heart looks like

  LikeClass({this.liked});

  @override
  _LikeClassState createState() => new _LikeClassState();
}

class _LikeClassState extends State<LikeClass> {
  bool liked;
  @override
  void initState() {
    liked=widget.liked;
  }
  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new Column(
        children: <Widget>[
          new GestureDetector(
            onTap:((){
              setState(() {
                liked=!liked;
                //widget.liked=!widget.liked;
              });
            }),
            child: new Icon(Icons.favorite, size: 24.0,
              color: liked?Colors.red:Colors.grey,
              //color: widget.liked?Colors.red:Colors.grey,//final method to control the appearance
            ),
          ),
        ],
      ),
    );
  }
}

推荐答案

您必须将状态(收藏夹与否)存储在父窗口小部件中. ListView.builder小部件可根据需要创建和销毁项目,销毁项目时将丢弃状态.这意味着列表项应该始终是无状态的小部件.

You have to store the state (favorite or not) in a parent widget. The ListView.builder widget creates and destroys items on demand, and the state is discarded when the item is destroyed. That means the list items should always be stateless widgets.

这是一个具有交互性的示例:

Here is an example with interactivity:

class Item {
  Item({this.name, this.isFavorite});

  String name;
  bool isFavorite;
}

class MyList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyListState();
}

class MyListState extends State<MyList> {
  List<Item> items;

  @override
  void initState() {
    super.initState();

    // Generate example items
    items = List<Item>();
    for (int i = 0; i < 100; i++) {
      items.add(Item(
        name: 'Item $i',
        isFavorite: false,
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        return ListItem(
          items[index],
          () => onFavoritePressed(index),
        );
      },
    );
  }

  onFavoritePressed(int index) {
    final item = items[index];
    setState(() {
      item.isFavorite = !item.isFavorite;
    });
  }
}

class ListItem extends StatelessWidget {
  ListItem(this.item, this.onFavoritePressed);

  final Item item;
  final VoidCallback onFavoritePressed;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(item.name),
      leading: IconButton(
        icon: Icon(item.isFavorite ? Icons.favorite : Icons.favorite_border),
        onPressed: onFavoritePressed,
      ),
    );
  }
}

这篇关于滚动后如何保持小部件的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆