Как выбрать одну кнопку переключения одновременно? - PullRequest
0 голосов
/ 03 мая 2020

Я работаю над приложением Flutter. Как выбрать одну кнопку переключения за раз, если у меня несколько кнопок переключения?

Проблема в том, что у меня есть несколько вариантов с несколькими вариантами в каждом случае, У меня 5 разных дел.

 onPressed: (int index) {
                setState(() {
                  isSelected2[index] = !isSelected2[index];

                  switch (index) {

                    //This is the other area I had to make changes
                    case 0:
                      if (isSelected2[index]) {
                        print('true');

                        _choiceA += 5;
                        _choiceB += 5;
                        _choiceC += 10;
                        _choiceD += 10;
                      } else {
                        print('false');
                        _choiceA += -5;
                        _choiceB += -5;
                        _choiceC += -10;
                        _choiceD += -10;
                      }
                      break;

Спасибо, Мухаммед

Ответы [ 2 ]

1 голос
/ 03 мая 2020

Проверьте код ниже:

import 'package:flutter/material.dart';

void main() => runApp(App());

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SamplePage(),
    );
  }
}

class SamplePage extends StatefulWidget {
  @override
  _SamplePageState createState() => _SamplePageState();
}

class _SamplePageState extends State<SamplePage> {
  List<bool> isSelected;

  @override
  void initState() {
    // this is for 3 buttons, add "false" same as the number of buttons here
    isSelected = [true, false, false];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('ToggleButtons Demo'),
      ),
      body: Center(
        child: ToggleButtons(
          children: <Widget>[
            // first toggle button
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'First',
              ),
            ),
            // second toggle button
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Second',
              ),
            ),
            // third toggle button
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(
                'Third',
              ),
            ),
          ],
          // logic for button selection below
          onPressed: (int index) {
            setState(() {
              for (int i = 0; i < isSelected.length; i++) {
                isSelected[i] = i == index;
              }
            });
          },
          isSelected: isSelected,
        ),
      ),
    );
  }
}

Выход:
enter image description here

1 голос
/ 03 мая 2020

Вам нужно отключить все остальные, чтобы добиться желаемого поведения. Составьте список значений, которые вы хотите обновить для каждого индекса кнопки:

List values = [[5,5,10,10], [3,2,3,-5], [3,-1,3,4], [3,-8, 12,1]];

Затем обновите ваш выбор:

onPressed: (int index) {
    setState(() {
      for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
        if (buttonIndex == index) {
          isSelected[buttonIndex] = !isSelected[buttonIndex];
          if(isSelected[buttonIndex]){
            _choiceA += values[buttonIndex][0];
            _choiceB += values[buttonIndex][1];
            _choiceC += values[buttonIndex][2];
            _choiceD += values[buttonIndex][3];
          }else{
            _choiceA -= values[buttonIndex][0];
            _choiceB -= values[buttonIndex][1];
            _choiceC -= values[buttonIndex][2];
            _choiceD -= values[buttonIndex][3];
            isSelected[buttonIndex] = false;
          }
        } else {
          if(isSelected[buttonIndex]){
            _choiceA -= values[buttonIndex][0];
            _choiceB -= values[buttonIndex][1];
            _choiceC -= values[buttonIndex][2];
            _choiceD -= values[buttonIndex][3];
            isSelected[buttonIndex] = false;
          }  
        }
      }
    });
  },

Редактировать: Этот код должен быть реорганизован

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...