Search code examples
flutterdartflutter-layout

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


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?
          }),
    ]));
  }
}

Solution

  • 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++;
                }
              });
            },
          ),