main.dart

import 'package:flutter/material.dart';
import 'package:untitled/home.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const HomePage();
  }
}


home.dart

import 'package:flutter/material.dart';
import 'package:untitled/imageWidgetStateful.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});
  @override
  State<StatefulWidget> createState() => _HomePage();
}

class _HomePage extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "HomePage",
      home: Scaffold(
        appBar: AppBar(title: const Text("HomePage Appbar")),
        body: const Column(
          children: [Text("ImageWidget"), BannerWidgetStateful()],
        ),
      ),
    );
  }
}


imageWidgetStateful.dart

import 'package:flutter/material.dart';

const image1 =
    "https://blog.meowrain.cn/api/i/2024/09/19/auLCNe1726729742207665842.webp";
const image2 =
    "https://blog.meowrain.cn/api/i/2024/09/30/0ok6S01727659729474010942.webp";

class BannerWidgetStateful extends StatefulWidget {
  const BannerWidgetStateful({super.key});

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

class _BannerWidgetStateful extends State<BannerWidgetStateful> {
  String? imgUrl;

  @override
  Widget build(BuildContext context) {
    return Container(
        width: 500,
        height: 500,
        child: Column(
          children: [
            ElevatedButton(
                onPressed: () {
                  setState(() {
                    imgUrl = imgUrl == image1 ? image2 : image1;
                  });
                },
                child: const Text("切换图片")),
            Image.network(imgUrl ?? image1)
          ],
        ));
  }
}