Flutter - Change one image to another in a short period of time

Asked

Viewed 332 times

0

Everybody, good afternoon, everybody!

  • I have a grid with 2 items set with "on tap" to perform an action.

  • These items have an image coming from /Assets.png and wanted the image to change to another image with a duration of 3 seconds and return to the previous image.

  • The idea is an image of a red lock being clicked and it turns green for 3 seconds and returns to the red lock.

class ListaReceivers extends StatelessWidget {
  ListaReceivers();

  @override
  Widget build(BuildContext context) {
    return AmbientMode(
      builder: (context, mode) =>
          mode == Mode.active ? HomeRoute() : AmbientWatchFace(),
    );
  }
}

@override
class HomeRoute extends StatelessWidget {
  final List<Device> devices = new List();

  soundBtn(String icon, Device device, String title, BuildContext context) {
    return GestureDetector(
      onTap: () async {
        var deviceRelay = new DeviceRelay(device.idDevice, device.id);
        var msg = await DeviceService.executarRelay(deviceRelay);
        alert(context, msg);
      },
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 8.0),
            child: Image.asset(
              'assets/icons/$icon.png',
              scale: 1.6,
            ),
          ),
          Text(title.toUpperCase(),
              style: TextStyle(
                  color: Colors.white, fontSize: 16, letterSpacing: 0))
        ],
      ),
    );
  }

  @override
  build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xff242424),
        resizeToAvoidBottomInset: true,
        resizeToAvoidBottomPadding: true,
        appBar: AppBar(
          iconTheme: IconThemeData(
            color: Colors.white, // Alterar cor da seta "Voltar"
          ),
          centerTitle: true,
          title: new Text("Zona - Expositor Geral",
              style: TextStyle(color: Colors.white)),
          flexibleSpace: Container(
            decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: <Color>[Color(0xff003ca6), Color(0xff032052)])),
          ),
        ),
        body: Padding(
          padding: EdgeInsets.only(top: 1),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                '',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                    fontWeight: FontWeight.w600),
              ),
              StreamBuilder(
                  stream: DeviceService.listDevices().asStream(),
                  builder: (BuildContext context, AsyncSnapshot snapshot) {
                    if (snapshot.data != null && snapshot.data.length > 0)
                      return Container(
                          width: MediaQuery.of(context).size.width,
                          height: MediaQuery.of(context).size.height * .7,
                          child: GridView.builder(
                              padding: EdgeInsets.all(10),
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      crossAxisSpacing: 10,
                                      mainAxisSpacing: 10),
                              itemCount: snapshot.data.length,
                              itemBuilder: (context, index) {
                                return Center(
                                    child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    soundBtn(
                                        'porta',
                                        snapshot.data[index],
                                        snapshot.data[index].deviceReceiverName,
                                        context),
                                  ],
                                ));
                              }));
                    else
                      return Center(child: CircularProgressIndicator());
                  }),
            ],
          ),
        ));
  }
}

1 answer

0


There are a few ways to do this, you can create the padlock as Component Statefulwidget. That way it would be something like this:

class Cadeado extends StatefulWidget {
  Cadeado({Key key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => CadeadoState();
}

class CadeadoState extends State<Cadeado>{

  Color color = Colors.red;
  void changeColor(Color newColor) {
    setState(() {
      color = newColor;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
      width: 200,
      height: 200
    );
  }
}

Then to use can be something like this:

class MyWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    GlobalKey<CadeadoState> key = GlobalKey();

    return Column(
      children: <Widget>[
        Cadeado(
          key: key,
        ),
        RaisedButton(
          onPressed: () async {
            key.currentState.changeColor(Colors.green);
            await Future.delayed(Duration(seconds: 3));
            key.currentState.changeColor(Colors.red);
          },
        )
      ],
    );
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.