0

在此处输入图像描述

我无法嵌入图像,因为我没有 10 名声望。我想在单击切换按钮时加载图像。对你来说似乎很简单,但对我来说很难做到。我是初学者。我不知道怎么写 onPressed 按钮。我已经为切换按钮编写了 onPressed 按钮。似乎不可能再写一个受压迫的代码。我已经使用 onpressedbutton 代码来使用 ToggleButton,但是我需要一个更多的函数来加载图像但我不知道该怎么做

enter code here

import 'package:flutter/material.dart';
import '123.dart';
import '456.dart';

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

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

class _MyAppState extends State<MyApp> {


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('imageToggle'),),
        body: Column(
          children: [
            Expanded(child: Image.asset('images/meow.jpg')),
            Button123(
            ),
            Button456(),

          ],
        ),
      ),
    );
  }
}

class Button456 extends StatefulWidget {
  @override
  _Button456State createState() => _Button456State();
}

class _Button456State extends State<Button456> {
  List<bool> isSelected = List.generate(3, (index) => false);
  @override
  Widget build(BuildContext context) {
    return Container(
        child: ToggleButtons(
          isSelected: isSelected,
          color: Colors.black,
          fillColor: Colors.grey,
          children: [
            Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Text('cat1'),),
            Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Text('cat2'),),
            Padding(padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Text('cat3'),),


          ],
          onPressed: (int newIndexx) {
            setState(() {
              for (int index = 0; index < isSelected.length; index++) {
                if (index == newIndexx) {
                  isSelected[index] = true;
                } else {
                  isSelected[index] = false;
                }
              }
            });
          },
        )
    );
  }
}
4

1 回答 1

0

您可以将图像 url 设为变量。

String imageLink = 'myImage.png';


class _MyAppState extends State<MyApp> {
    onButtonPressed(String value) {
       setState(() {imageLink = value});
    }

    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
            appBar: AppBar(title: Text('imageToggle'),),
            body: Column(
                children: [
                   Expanded(child: Image.asset(imageLink)),
                   TextButton(child: Text('Click Me!'), onPressed: onButtonPressed('newImageLink')),
                ],
            ),
          ),
      );
   }
}
于 2021-05-21T13:44:38.203 回答