0

Galera!

  • Tenho uma grid com 2 itens setados com "on tap" para executar uma ação.

  • Esses itens tem uma imagem vinda de /assets.png e queria que a imagem mudasse para outra imagem com uma duração de 3 segundos e voltasse para a imagem anterior.

  • A ideia é uma imagem de um cadeado vermelho ser clicado e ele fica verde por 3 segundos e retorna ao cadeado vermelho.

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 Resposta 1

0

Há algumas formas de fazer isso, você pode criar o cadeado como component StatefulWidget. Dessa forma seria algo desse tipo:

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
    );
  }
}

Depois pra usar pode ser algo desse tipo:

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);
          },
        )
      ],
    );
  }
}
1
  • 1
    Poxa, é isso! Fiz dessa forma e deu certo aqui, agradeço pela atenção amigo! 2/04/2020 às 19:52

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .