2017-09-05 79 views
0

我有一個按鈕,有一個圖像作爲一個孩子。我需要它,以便在按下按鈕的同時,圖像變爲另一個圖像,並且當用戶停止按下按鈕時,圖像會返回到其原始圖像。如何製作一個帶有顫動圖像的按鈕,當somone按下時突出顯示圖像?

基本上我希望它像一個凸起的按鈕,但與自定義圖像的凸起和按下狀態。

下面是相關代碼:

class LoginButton extends StatefulWidget { 
    @override 
    _LoginButtonState createState() => new _LoginButtonState(); 
} 

class _LoginButtonState extends State<LoginButton> { 
    void _onClicked() { 
    setState(() { 
     //I don't know what I should put here to cause the image to redraw 
     //only on button press 

    }); 
    } 

    @override 
    Widget build(BuildContext context) { 
    var assetImage = new AssetImage("assets/loginscreen/btn.png"); 
    var image = new Image(image: assetImage, height: 50.0, width: 330.0); 
    return new Container(
     height: image.height, 
     width: image.width, 
     child: new FlatButton(
     onPressed: _onClicked, 
     child: new ConstrainedBox(
      constraints: new BoxConstraints.expand(), 
      child: image, 
     ), 
    ), 
    ); 
    } 
} 
+0

我有更多的相關代碼的答案更新,你想達到的目標。 – aziza

回答

1

您可以定義默認的圖像作爲這樣的類_LoginButtonState的屬性

class _LoginButtonState extends State<LoginButton> { 
String _myImage = "assets/loginscreen/btn.png"; ... } 

現在你_onClick方法應包含狀態的變化,只需使用if條件就可以將_myImage的字符串更改爲新圖像

void _onClicked() { 
     setState(() { 
      if (_myImage == "assets/loginscreen/btn.png"){ 
      _myImage = "<my new asset>"; //change myImage to the other one 
      } 
      else { 
       _myImage = "assets/loginscreen/btn.png"; //change myImage back to the original one 
       } 
     }); 
     } 

和窗口小部件的構建中:

var assetImage = new AssetImage(_myImage); 

================================= ==============================================================

更新

我設法做了一個類似的想法,你試圖實現使用GesutureDetector,這裏我用顏色來測試它,但它不應該像改變圖像的鏈接那麼不同,雖然我知道esume重新繪製圖像比改變顏色要慢。

以下是完整的代碼,我用:

import 'package:flutter/material.dart'; 

void main() { 
    runApp(new MaterialApp(
    home: new MyApp(), 
)); 
} 

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

class _MyAppState extends State<MyApp> { 
    var _myColor = Colors.blue; 


    @override 
    Widget build(BuildContext context) { 
    return new Scaffold(
     appBar: new AppBar(
     title: new Text ("Tap me!"), 
     centerTitle: true, 
    ), 
     body: new GestureDetector(
     onTapDown:(TapDownDetails details) { setState(() { 
     _myColor = Colors.orange; 
    }); 
     }, 
     onTapUp: (TapUpDetails details) { 
      setState(() { 
      _myColor = Colors.blue; 
      }); 
     }, 

     child: new Container (
      color: _myColor, 
     ), 
    ), 
    ); 
    } 
} 
+0

我在發佈這個答案後發現帖子中有更新,我不確定您的意思是在未按下時更改回來嗎? – aziza

+0

感謝您的答案,但我希望圖像只在按下時重新繪製,並且當按鈕沒有被按下時變回原始圖像 –

+0

我試圖模擬一個正常的按鈕,當按下somone時按下它時,當somone不再按下時,它會回到未按下的狀態 –