当容器在 ListView 中处于活动状态或非活动状态时,如何更改容器的颜色

时间:2021-01-20 22:34:32

标签: flutter

当用户当前选择容器时,我尝试更改容器的活动和非活动颜色,如果我必须提供更多详细信息,我有 listView 水平显示 10 个图像,我通过 for 循环获取这些图像,我只想要它用户选择一张图片,图片父容器颜色应该不同,以便用户理解当前选择,但是当用户按下其他图片时,应该只显示该图片的活动颜色,我该怎么做,谢谢您的帮助..

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'constants.dart';
import 'dart:math';

enum Sticker{
sticker1,sticker2,sticker3,sticker4,sticker5,sticker6,sticker7,sticker8,sticker9,
}
class AddMenuScreen extends StatefulWidget {
  @override
  _AddMenuScreenState createState() => _AddMenuScreenState();
}

class _AddMenuScreenState extends State<AddMenuScreen> {
  Color _animatedContainerForStickersInactiveColor=Colors.white;
  Color _animatedContainerForStickersActiveColor=kColorTheme2;
  String chosenImagePath;
  List<Widget> stickerList=[];
  String menuName;
  int addScreenImageNum;

  void initState(){
    super.initState();
    createAddScreenImageNum();
    makeStickersWithFlatButton();
  }

  void createAddScreenImageNum(){
    Random random =Random();
    addScreenImageNum = random.nextInt(3)+1;
  }
  void makeStickersWithFlatButton(){
    for(int i=1;i<10;i++){
      stickerList.add(Container(
        color: chosenImagePath=="images/sticker$i.png"?
        _animatedContainerForStickersActiveColor:_animatedContainerForStickersInactiveColor,
        child: FlatButton(
          child: Image(image: AssetImage("images/sticker$i.png")),
          onPressed:(){
            setState(() {
              chosenImagePath="images/sticker$i.png";
            });
            },
          ),
      ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: kColorTheme9,
      child: Container(
        height: 400,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(topRight: Radius.circular(40),topLeft: Radius.circular(40)),
        ),
        child:Padding(
          padding:EdgeInsets.all(20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                decoration: BoxDecoration(
                  color: kColorTheme2,
                  borderRadius: BorderRadius.circular(90)
                ),
                child: TextField(
                  style: TextStyle(
                    color: Colors.black,
                    fontFamily:"Graduate",
                    fontSize: 20,
                  ),
                  textAlign: TextAlign.center,
                  onChanged: (value){
                    menuName=value;
                  },
                  decoration: InputDecoration(
                    border:OutlineInputBorder(
                      borderRadius: BorderRadius.circular(90),
                      borderSide: BorderSide(
                      color: Colors.teal,
                      ),
                    ),
                    hintText: "Menü ismi belirleyin",
                    hintStyle: TextStyle(
                      color: Colors.black.withOpacity(0.2),
                      fontFamily: "Graduate",
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20,),
              Text("menünüz icin yana kadırarak bir resim secin",textAlign: TextAlign.center,
                style: TextStyle(fontFamily: "Graduate", fontSize: 12),),
              SizedBox(height: 20,),
              Expanded(
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  children: stickerList,
                ),
              ),
              SizedBox(height: 20,),
              Container(
                decoration: BoxDecoration(
                  border: Border.all(style: BorderStyle.solid),
                  color: kColorTheme7,
                  borderRadius: BorderRadius.circular(90),
                ),
                child: FlatButton(
                  onPressed: (){
                  },
                  child: Text("Menu ekle", style: TextStyle(fontSize: 20, color:  Colors.white,
                      fontFamily: "Graduate", fontWeight: FontWeight.bold),),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

2 个答案:

答案 0 :(得分:1)

尝试将您的容器包装在 InkWell 中,您可以在其中指定 onTap 功能。从那里你可以像这样更新你的容器颜色:

const mongoose = require('mongoose')

const connectDB = async () => {
    try {
        const conn = await mongoose.connect(process.env.MONGO_URI, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false
        })

        console.log(`${conn.connection.host}`)
    } catch (err) {
        console.log(err)
    }
}

module.exports = connectDB

您也可以尝试创建自己的类,然后使用 ListView.builder() 构建它,这将为您提供项目的索引。然后你可以指定一个 onTap,正如我之前在你自己的课程中提到的那样,并相应地处理颜色。再次点击后,您只需将所有其他颜色恢复正常

答案 1 :(得分:1)

您没有让列表再次重建以进行新的更改。因此,在 initState 中,所有列表小部件都在 setState 中创建一次。所以对 var selectedIndex = -1; ... Expanded( child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: =====> YOUR LIST COUNT <=====, itemBuilder: itemBuilder: (context, index) { return Container( color: index == selectedIndex ? activeColor : passiveColor child: FlatButton( onPressed:(){ setState(() { selectedIndex = index; }); },) ); }, ), ), 的任何调用都没有影响

list of lists