Home > Net >  How can ı make changes color when ı click on container in flutter?
How can ı make changes color when ı click on container in flutter?

Time:11-13

I wrote the code in general,but how can ı make a container that changes color with the first pink,then red, green,blue and again pink,then red, green,blue every time ı click on a container using inkwell?

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: MyApp(),
      ),
    ),
  );
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int index = 0;
  List<Color> mycolors = [
    Colors.pink,
    Colors.red,
    Colors.green,
    Colors.blue,
  ];
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Wrap(children: [
      InkWell(
          child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.all(5),
            height: 100,
            width: 100,
          ),
          onTap: () {
            //how canı write a code?
          }),
    ]));
  }
}

CodePudding user response:

Just increment the index and if it exceeds the length make it 0

onTap: () {
  index  ;
  if (index >= mycolors.length) index = 0;
  setState(() {});
},

And use

child: Container(
    color: mycolors[index],

CodePudding user response:

Change your list to this:

List<Map<String, dynamic>> mycolors = [
    {"name": "Pink", "color": Colors.pink},
    {"name": "Red", "color": Colors.red},
    {"name": "Green", "color": Colors.green},
    {"name": "Blue", "color": Colors.blue}
  ];

then use it like this:

InkWell(
        child: Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(5),
          height: 100,
          width: 100,
          color: mycolors[index]['color'],
          child: Text(mycolors[index]['name']),
        ),
        onTap: () {
          setState(() {
            if (index == 3) {
              index = 0;
            } else {
              index  ;
            }
          });
        },
      ),
  • Related