按下时如何在抖动中改变图像?

时间:2020-11-12 05:46:19

标签: flutter flutter-layout flutter-animation

因此,我对抖动开发非常陌生,并且我对按下按钮时如何更改图像有疑问。因此,我喜欢3张图像,并且我希望在单击第1张图像时显示3张图像中的任何随机图像。 我将附加部分代码。

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        children: [
          Expanded(
              child: FlatButton(
            onPressed: () {},
            child: Image.asset('images/image1.png'),
          ))
        ],
      ),
    );

2 个答案:

答案 0 :(得分:1)

首先,您可以将'images/image1.png'存储为变量

String default_image = 'images/image1.png';

然后将图像部分更改为此

 Expanded(
            child: FlatButton(
             onPressed: () {
                 setState((){
                      default_image = "images/image-2.png";
                   });
                 },
                child: Image.asset(default_image),
    ),
  )

答案 1 :(得分:0)

我希望它是有状态的小部件,请先使其具有状态

import * as React from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function App({ navigation }) {
  const [state, dispatch] = React.useReducer(
    (prevState, action) => {
      switch (action.type) {
        case 'RESTORE_TOKEN':
          return {
            ...prevState,
            userToken: action.token,
            isLoading: false,
          };
        case 'SIGN_IN':
          return {
            ...prevState,
            isSignout: false,
            userToken: action.token,
          };
        case 'SIGN_OUT':
          return {
            ...prevState,
            isSignout: true,
            userToken: null,
          };
      }
    },
    {
      isLoading: true,
      isSignout: false,
      userToken: null,
    }
  );

  React.useEffect(() => {
    // Fetch the token from storage then navigate to our appropriate place
    const bootstrapAsync = async () => {
      let userToken;

      try {
        userToken = await AsyncStorage.getItem('userToken');
      } catch (e) {
        // Restoring token failed
      }

      
      dispatch({ type: 'RESTORE_TOKEN', token: userToken });
    };

    bootstrapAsync();
  }, []);

  const authContext = React.useMemo(
    () => ({
      signIn: async data => {
      // store token in Async storage
        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
      signOut: () => dispatch({ type: 'SIGN_OUT' }),
      signUp: async data => {
        // Remove token from Async storage
        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      <Stack.Navigator>
        {state.userToken == null ? (
          <Stack.Screen name="SignIn" component={SignInScreen} />
        ) : (
          <Stack.Screen name="Home" component={HomeScreen} />
        )}
      </Stack.Navigator>
    </AuthContext.Provider>
  );
}