Flutter按钮可在其上方显示图像



大家好,我希望大家好。我想知道如何创建一个按钮,当它被按下时,显示一个图像和一列或一行。

请帮帮我。

**现在,当按下按钮时,图像出现并消失。但它不会刷新以获得新的(它是一个动态URL(

***现在按下按钮时图像会发生变化,但我不知道该把按钮放在哪里。

更新代码5.0

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'colors.dart';
const String url = 'http://thecatapi.com/api/images/get?format=src&type=gif';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme:
ThemeData(primarySwatch: primaryBlack, accentColor: Colors.white),
debugShowCheckedModeBanner: false,
home: HomePage());
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late Uint8List bytes;
bool loading = true;
@override
void didChangeDependencies() async {
getBytes();
super.didChangeDependencies();
}
void getBytes() async {
setState(() {
loading = true;
});
Uint8List newbytes = (await NetworkAssetBundle(Uri.parse(url)).load(url))
.buffer
.asUint8List();
setState(() {
bytes = newbytes;
loading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
':(:',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text('FelizTriste'),
Text(':(:', style: TextStyle(fontWeight: FontWeight.bold)),
],
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
loading
? const SizedBox(
width: 355,
height: 355,
child: Center(child: CircularProgressIndicator()))
: Container(
decoration: BoxDecoration(
border: Border.all(color: primaryBlack, width: 6)),
child: Image.memory(
bytes,
width: 350,
height: 350,
fit: BoxFit.cover,
),
),
SizedBox(
height: 60,
),
ElevatedButton(onPressed: getBytes, child: const Text('GATIT@S')),
const Text(
'¿Quieres ver gatit@s?',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
)
],
),
),
);
}
}

我试着添加一个容器,目的是减少或增加图像,使其完美贴合,但没有成功。

此外,URL是动态的,所以我想";刷新";每个按钮的图像显示希望你能帮助我。

要学习此方法:Flutter:刷新网络图像

我修改了您的代码:

  1. 删除了image函数,而是创建一个变量boolshowImage,该变量最初应该为false。

  2. 按下按钮后,showImage应更改为true。

    ElevatedButton(
    onPressed: () {
    setState(() {
    showImage = true;
    });
    },
    child: Text('GATIT@S')
    ),
    
  3. 只有当showImage变量为true时,才应显示图像和文本,否则显示空的SizedBox((。

    showImage
    ? Column(
    children: [
    Image.network(           'https://docs.flutter.dev/assets/images/dash/dash-fainting.gif'),
    Text('Hola')
    ],
    )
    : SizedBox(
    height: 0,
    ),
    

最新更新