Home > other >  how to prevent to change colour while list view scroll
how to prevent to change colour while list view scroll

Time:09-11

I have created a demo

I have set colour as random for each container of list view, so it changes colours whenever I scroll ,

I want to prevent changing colour while scrolling,

Like if first container colour is red then it should b not changed until I restart app,

I placed print statement inside build method...but it showing only once, than why container's colour get changed,

if it rebuilds, it should execute print statement more than one time

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: 10,
          itemBuilder: (context,index){
        return Container(
          height: 200,
          color: Color.fromRGBO(Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), 1),
       );
      }),
    );
  }

CodePudding user response:

In ListView.builder items won't be alive for performance matter, every time you scroll, it build those item. try this:

@override
  Widget build(BuildContext context) {
    var colorList =  List<Color>.generate(10, (index) => Color.fromRGBO(Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), 1)).toList();
    return Scaffold(
      body: ListView.builder(
          itemCount: colorList.length,
          itemBuilder: (context,index){
        return Container(
          height: 200,
          color: colorList[index],
       );
      }),
    );
  }
  • Related