dart Flutter:获取选定容器的值

tktrz96b  于 2023-02-20  发布在  Flutter
关注(0)|答案(1)|浏览(127)

我正在尝试获取GridView中所选容器的文本值。我可以打印所选索引。但我需要获取所选容器的文本值,以便将其保存在sharedPreferences中,稍后获取并存储在服务器上。
请协助。您的帮助将不胜感激。

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

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

  @override
  State<QuickSurveyScreen> createState() => _QuickSurveyScreenState();
}

class _QuickSurveyScreenState extends State<QuickSurveyScreen> {
  int selectedIndex = -1;

  List<String> gasUsage = [
    "Heater",
    "Stove",
    "Geyser",
    "Fireplace",
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(
                child: Padding(
              padding: const EdgeInsets.only(top: 120.0, right: 30, left: 30),
              child: Column(
                children: const [
                  Text(
                    "What do you use \nLP Gas for?",
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                      vertical: 16.0,
                      horizontal: 20,
                    ),
                    child: Text(
                      "Please choose one or more options from below",
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 18,
                      ),
                    ),
                  ),
                ],
              ),
            ))
          ];
        },
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: Column(
              children: [
                Expanded(
                  child: GridView.builder(
                      gridDelegate:
                          const SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        childAspectRatio: 1.0,
                        crossAxisSpacing: 20.0,
                        mainAxisSpacing: 20.0,
                      ),
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: gasUsage.length,
                      itemBuilder: (BuildContext context, int index) {
                        return gasUsageContainer("", gasUsage[index], index);
                      }),
                ),
                ElevatedButton(
                  onPressed: () {},
                  style: ElevatedButton.styleFrom(
                    minimumSize: const Size(double.infinity, 65.0),
                    backgroundColor: const Color(0xFFF0A202),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(26.0),
                    ),
                    textStyle: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  child: const Text('Continue'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  gasUsageContainer(String image, String name, int index) {
    return GestureDetector(
      onTap: () {
        setState(() {
          if (selectedIndex == index) {
            selectedIndex = -1;
          } else {
            selectedIndex = index;
          }
          if (kDebugMode) {
            print(selectedIndex);
          }
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        padding: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          color: selectedIndex == index
              ? Colors.amber.shade50
              : Colors.grey.shade200,
          border: Border.all(
            color: selectedIndex == index
                ? Colors.amber
                : Colors.blue.withOpacity(0),
            width: 2.0,
          ),
          borderRadius: BorderRadius.circular(22.0),
        ),
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                name,
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: selectedIndex == index
                      ? Colors.amber.shade800
                      : Colors.black,
                ),
              )
            ]),
      ),
    );
  }
}
qni6mghb

qni6mghb1#

您可以使用indexList获得它。请查看我在gasUsageContainer中对onTap所做的更改

onTap: () {
        setState(() {
          String? selected;
          if (selectedIndex == index) {
            selectedIndex = -1;
            selected = null;
          } else {
            selectedIndex = index;
            selected = gasUsage[index];//Here you get the value
          }
          if (kDebugMode) {
            print('selectedIndex:$selectedIndex, selected: $selected');
          }
        });
      }
    • 已编辑**
class _QuickSurveyScreenState extends State<QuickSurveyScreen> {
  final selectedItems = <String>[];
  ...

  gasUsageContainer(String image, String name, int index) {
    String item = gasUsage[index];
    return GestureDetector(
      onTap: () {
        setState(() {
          if (selectedItems.contains(item)) {
            selectedItems.remove(item);
          } else {
            selectedItems.add(item);
          }
          if (kDebugMode) {
            print('selectedItems: $selectedItems');
          }
        });
      },
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        padding: const EdgeInsets.all(10.0),
        decoration: BoxDecoration(
          color: selectedItems.contains(item)
              ? Colors.amber.shade50
              : Colors.grey.shade200,
          border: Border.all(
            color: selectedItems.contains(item)
                ? Colors.amber
                : Colors.blue.withOpacity(0),
            width: 2.0,
          ),
          borderRadius: BorderRadius.circular(22.0),
        ),
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                name,
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: selectedItems.contains(item)
                      ? Colors.amber.shade800
                      : Colors.black,
                ),
              )
            ]),
      ),
    );
  }
}

相关问题