首页 > 解决方案 > 如何在 Flutter 中动态设置 CupertinoSwitch(映射)值?

问题描述

创建动态列表(请求),我在那里放了一个开关。但是,开关拒绝显示其预期状态(单击时状态不会改变。)

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:scat/request.dart' as request;
import 'package:scat/util.dart' as util;

class _ConfigPushState extends State<ConfigPush> {
  Future<request.ApiResult> configList;
  Map<String, bool> _onOffMap = {};
  @override
  void initState() {
    super.initState();
    configList = request.configList();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(50.0), // here the desired height
        child: new AppBar(
          backgroundColor: Colors.black,
          leading: new IconButton(
            icon: new Icon(Icons.close),
            onPressed: () => Navigator.of(context).pop(),
          ),
          centerTitle: true,
          title: new Text('API 설정', style: util.appTitleStyle),
        ),
      ),
      body: Center(
          child: FutureBuilder<request.ApiResult>(
              future: configList,
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return CircularProgressIndicator();
                }
                if (snapshot.hasError) {
                  return CircularProgressIndicator();
                }
                _onOffMap = {};
                return ListView.separated(
                    separatorBuilder: (context, index) => Divider(),
                    itemCount: snapshot.data.data.length,
                    itemBuilder: (context, index) {
                      var row = snapshot.data.data[index];

                      var type = row['type'] as String;
                      var value = row['value'] as bool;
                      var disabled = row['isDisabled'] as bool;
                      var subtitle = disabled ? '아직 준비중' : row['description'];
                      _onOffMap[type] = value;
                      // _arr.add(value);
                      // _lights = value;

                      print('item builder ${type}');
                      return Container(
                          height: util.isEmpty(subtitle) ? 50 : 70,
                          child: new ListTile(
                            title: new Text(row['name']),
                            subtitle: new Text(subtitle),
                            trailing: CupertinoSwitch(
                              activeColor: Colors.deepPurple,
                              // value: _arr[index],
                              // value: _lights,
                              value: _onOffMap[type],
                              onChanged: (bool value) {
                                setState(() {
                                  if (disabled) {
                                    Scaffold.of(context).showSnackBar(
                                        SnackBar(content: Text('개발중..')));
                                    return;
                                  }

                                  // _lights = value;
                                  print("before $_onOffMap $type");
                                  _onOffMap[type] = value;
                                  print("after $_onOffMap");

                                  request
                                      .pushSet(type, value.toString(), "", "")
                                      .then((a) {
                                    Scaffold.of(context).showSnackBar(
                                        SnackBar(content: Text('처리 되었습니다.')));
                                  });
                                });
                              },
                            ),
                          ));
                    });
              })),
    );
  }
}

标签: flutterdart

解决方案


试试这个,我希望它对你有用:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:scat/request.dart' as request;
import 'package:scat/util.dart' as util;

class _ConfigPushState extends State<ConfigPush> {
  Future<request.ApiResult> configList;
  Map<String, bool> _onOffMap = {};
  @override
  void initState() {
    super.initState();
    configList = request.configList();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(50.0), // here the desired height
        child: new AppBar(
          backgroundColor: Colors.black,
          leading: new IconButton(
            icon: new Icon(Icons.close),
            onPressed: () => Navigator.of(context).pop(),
          ),
          centerTitle: true,
          title: new Text('API 설정', style: util.appTitleStyle),
        ),
      ),
      body: Center(
          child: FutureBuilder<request.ApiResult>(
              future: configList,
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return CircularProgressIndicator();
                }
                if (snapshot.hasError) {
                  return CircularProgressIndicator();
                }
                _onOffMap = {
                   "type": true;
                };
                return ListView.separated(
                    separatorBuilder: (context, index) => Divider(),
                    itemCount: snapshot.data.data.length,
                    itemBuilder: (context, index) {
                      var row = snapshot.data.data[index];

                      var type = row['type'] as String;
                      var value = row['value'] as bool;
                      var disabled = row['isDisabled'] as bool;
                      var subtitle = disabled ? '아직 준비중' : row['description'];
                      _onOffMap["type"] = value;
                      // _arr.add(value);
                      // _lights = value;

                      print('item builder ${type}');
                      return Container(
                          height: util.isEmpty(subtitle) ? 50 : 70,
                          child: new ListTile(
                            title: new Text(row['name']),
                            subtitle: new Text(subtitle),
                            trailing: CupertinoSwitch(
                              activeColor: Colors.deepPurple,
                              // value: _arr[index],
                              // value: _lights,
                              value: _onOffMap["type"],
                              onChanged: (bool value) {
                                setState(() {
                                  if (disabled) {
                                    Scaffold.of(context).showSnackBar(
                                        SnackBar(content: Text('개발중..')));
                                    return;
                                  }

                                  // _lights = value;
                                  print("before $_onOffMap $type");
                                  _onOffMap["type"] = value;
                                  print("after $_onOffMap");

                                  request
                                      .pushSet(type, value.toString(), "", "")
                                      .then((a) {
                                    Scaffold.of(context).showSnackBar(
                                        SnackBar(content: Text('처리 되었습니다.')));
                                  });
                                });
                              },
                            ),
                          ));
                    });
              })),
    );
  }
}

推荐阅读